ASP.NET核心中的承载令牌认证

时间:2016-06-08 16:40:07

标签: c# asp.net-core

尝试在简单的.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 ;?我需要设置这个处理程序?

2 个答案:

答案 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;
});