我使用以下文章在我的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 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
}
一切正常 - 令牌已经发布且Authorize
工作正常,当我发出未经身份验证的请求时,我得到以下回复:
正如您所见Status = 401
,这意味着UnAuthenticated
- 但正如您所见,StatusText为空。
现在有很多原因可以解决为什么请求可能是UnAuthenticated,例如JWT Token expired
,我想要做的是根据服务器上的验证规则失败传递自定义状态文本,我该如何在MVC Core中执行此操作?