Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
Maxim Avatar asked Jun 08 '16 16:06

Maxim


People also ask

How do you authenticate a Bearer Token?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

What is Bearer Token authentication C#?

Bearer authentication (also called token authentication) is one of the HTTP authentication schemes that grant access to the bearer of this token. Bearer token authentication is done by sending a security token with every HTTP request we make to the server.


2 Answers

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();
like image 123
Kévin Chalet Avatar answered Sep 21 '22 05:09

Kévin Chalet


For .NET Core 3.0 you would need:

In ConfigureServices(IServiceCollection services):

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = issuer;
        options.Audience  = audience;
        options.TokenValidationParameters = tokenValidationParameters;
    });

In Configure(IApplicationBuilder app, IWebHostEnvironment env):

// Add it after app.UseRouting() and before app.UseEndpoints()! 
// Order of middlewares is important!
app.UseAuthentication();
app.UseAuthorization();

PS: To omit authentication scheme indication in [Authorize] attribute you could set the default authentication scheme in ConfigureServices(IServiceCollection services) in AuthenticationOptions options:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
});
like image 22
Alexander Goldabin Avatar answered Sep 22 '22 05:09

Alexander Goldabin