Bearer Token Authentication in ASP.NET Core

前端 未结 2 2009
陌清茗
陌清茗 2021-02-01 07:21

Trying to use bearer token based authentification in simple .Net Core Web API project. Here is my Startup.cs

app.UseMvc();
//---
const string secret         


        
相关标签:
2条回答
  • 2021-02-01 07:50

    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();
    
    0 讨论(0)
  • 2021-02-01 08:02

    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;
    });
    
    0 讨论(0)
提交回复
热议问题