Asp.net web api JWT令牌MVC核心的自定义状态文本
我使用以下文章在MVC核心应用程序中实现了JWT令牌身份验证: 这就是我的Asp.net web api JWT令牌MVC核心的自定义状态文本,asp.net-web-api,asp.net-core,jwt,asp.net-core-middleware,Asp.net Web Api,Asp.net Core,Jwt,Asp.net Core Middleware,我使用以下文章在MVC核心应用程序中实现了JWT令牌身份验证: 这就是我的Startup.cs中的内容 private const string SecretKey = "MySecretKey"; //TODO: remove hard coded get from environments as suggested in Blog private readonly SymmetricSecurityKey _signingKey = new SymmetricSecuri
Startup.cs中的内容
private const string SecretKey = "MySecretKey"; //TODO: remove hard coded get from environments as suggested in Blog
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
});
}
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(options => { });
services.Configure<MvcOptions>(options => { });
services.Configure<IISOptions>(options => { });
services.AddOptions();
#region Authentication and Authorisation
services.AddAuthorization(options =>
{
using (var dbContext = new FoodHouseContext(Configuration.GetConnectionString("DefaultConnection")))
{
var features = dbContext.Features.Select(s => s.Name).ToList();
foreach (var feature in features)
{
options.AddPolicy(feature, policy => policy.Requirements.Add(new FeatureRequirement(feature)));
}
}
});
// Configure JWT Token Settings
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});
#endregion
}
private const string SecretKey=“MySecretKey”//TODO:按照博客中的建议从环境中删除硬编码get
私有只读SymmetricSecurityKey _signingKey=新的SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
公共void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
var jwtappsetingoptions=Configuration.GetSection(nameof(jwtissueoptions));
var tokenValidationParameters=新的tokenValidationParameters
{
validateisuer=true,
ValidIssuer=jwtAppSettingOptions[名称(JwtIssuerOptions.Issuer)],
ValidateAudience=true,
ValidAudience=jwtAppSettingOptions[名称(JWTissueOptions.Audience)],
ValidateSuersigningKey=true,
IssuerSigningKey=\u signingKey,
RequireExpirationTime=true,
ValidateLifetime=true,
时钟偏移=时间跨度0
};
应用程序UseJWTBeareAuthentication(新JWTBeareOptions
{
自动验证=真,
自动挑战=正确,
TokenValidationParameters=TokenValidationParameters,
});
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
}
app.UseStaticFiles();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
routes.MapRoute(
名称:“区域路线”,
模板:“{area:exists}/{controller}/{action}”,
默认值:新建{controller=“Home”,action=“Index”}
);
});
}
public void配置服务(IServiceCollection服务)
{
//添加框架服务。
services.AddMvc(选项=>{});
Configure(选项=>{});
Configure(选项=>{});
services.AddOptions();
#地区认证和授权
services.AddAuthorization(选项=>
{
使用(var dbContext=newFoodhouseContext(Configuration.GetConnectionString(“DefaultConnection”))
{
var features=dbContext.features.Select(s=>s.Name.ToList();
foreach(特征中的var特征)
{
options.AddPolicy(feature,policy=>policy.Requirements.Add(newfeaturerequirement(feature));
}
}
});
//配置JWT令牌设置
var jwtappsetingoptions=Configuration.GetSection(nameof(jwtissueoptions));
配置(选项=>
{
options.Issuer=jwtappsetingoptions[名称(JwtIssuerOptions.Issuer)];
options.audition=jwtappsetingoptions[名称(jwtissueoptions.audition)];
options.SigningCredentials=新的SigningCredentials(_signingKey,SecurityAlgorithms.HmacSha256);
});
#端区
}
一切正常-令牌已发出且授权
正常工作,当我发出未经验证的请求时,我得到以下响应:
您可以看到Status=401
,这意味着未经验证
——但您可以看到Status文本为空
现在有很多原因导致请求未经身份验证,例如,JWT令牌已过期
,我想做的是在服务器上传递一个基于验证规则的自定义状态文本失败,我如何在MVC Core中做到这一点?据我所知,如果JWT身份验证失败,服务器发送一个响应401状态码和Www-Authenticate
头,如下所示:Www-Authenticate:Bearer error=“invalid\u token”,error\u description=“token还没有生效”
。您是否尝试从标头中获取错误描述
?@ademcaglin您是对的,错误消息在标头中…据我所知,如果jwt身份验证失败,服务器将发送一个401状态代码和Www Authenticate
标头,如下所示:Www Authenticate:Bearer error=“invalid_token”,错误描述=“令牌尚未生效”
。您是否尝试从标头获取错误描述?@ademcaglin您是对的错误消息在标头内。。。