Bearer Token Authentication in ASP.NET Core

Trying to use bearer token based authentification in simple .Net Core Web API project. Here is my 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,
});

Also i add AuthorizeAttribute to controllers action

[HttpGet]
[Authorize(ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IEnumerable<string> Get()
{
    return new[] { "value1", "value2" };
}

But when try to send get request with header Authorization: Bearer [TOKEN] i get exception

System.InvalidOperationException: No authentication handler is configured to authenticate for the scheme: Bearer
   at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.

So what is this 'authentication handler'? Where i need to set this handler?


In ASP.NET Core, the order of the middleware matters: they are executed in the same order as they are registered. Here, app.UseMvc() is called before the JWT bearer middleware, so this can't work.

Put app.UseMvc() at the end of your pipeline and it should work:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = tokenValidationParameters,
    AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
});

app.UseMvc();
链接地址: http://www.djcxy.com/p/22440.html

上一篇: .NET Web API 2 OWIN承载令牌认证

下一篇: ASP.NET核心中的持证人令牌认证