尝试在简单的.Net Core Web API项目中使用基于承载令牌的身份验证。这是我的Startup.cs
app.UseMvc();
//---
const string secretKey = "mysupersecret_secretkey!123";
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
//---
const string audience = "Audience";
const string issuer = "Issuer";
//---
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = false,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
AuthenticationType = JwtBearerDefaults.AuthenticationScheme
};
//---
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
});
我还将AuthorizeAttribute
添加到控制器操作
[HttpGet]
[Authorize(ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IEnumerable<string> Get()
{
return new[] { "value1", "value2" };
}
但是当尝试使用标头发送get请求时
Authorization: Bearer [TOKEN]
我得到例外
System.InvalidOperationException: No authentication handler is configured to authenticate for the scheme: Bearer
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.
那么这个&#39;身份验证处理程序&#39 ;?我需要设置这个处理程序?
答案 0 :(得分:26)
在ASP.NET Core中,中间件的顺序很重要:它们的执行顺序与注册顺序相同。这里,在JWT承载中间件之前调用app.UseMvc()
,因此这不起作用。
将app.UseMvc()
放在管道的末尾,它应该有效:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
});
app.UseMvc();
答案 1 :(得分:4)
对于 .NET Core 3.0 ,您需要:
在ConfigureServices(IServiceCollection services)
中:
services.AddAuthentication()
.AddJwtBearer(options =>
{
options.Authority = issuer;
options.Audience = audience;
options.TokenValidationParameters = tokenValidationParameters;
});
在Configure(IApplicationBuilder app, IWebHostEnvironment env)
中:
// Add it after app.UseRouting() and before app.UseEndpoints()!
// Order of middlewares is important!
app.UseAuthentication();
app.UseAuthorization();
PS:要在[Authorize]
属性中省略身份验证方案指示,可以在ConfigureServices(IServiceCollection services)
选项的AuthenticationOptions
中设置默认身份验证方案:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
});