ASP.NET Core 2.0 JWT Validation fails with `Authorization failed for user: (null)` error

后端 未结 11 1456
暗喜
暗喜 2020-12-08 18:38

I\'m using ASP.NET Core 2.0 application (Web API) as a JWT issuer to generate a token consumable by a mobile app. Unfortunately, this token couldn\'t be validated by one con

相关标签:
11条回答
  • 2020-12-08 18:58

    The sequence of the add statements in the configure function is of importance. Make sure that

    app.UseAuthentication();
    

    comes before

    app.UseMvc();
    

    Might this have been the problem?

    0 讨论(0)
  • 2020-12-08 19:01

    In your startup.cs ConfigureServices method if you add

    services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(options => ...
    

    Explanation: When you use [Authorize] on a controller it binds to the first authorization system by default.

    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    

    With this you are setting your default to JWT Bearer authentication.

    additionally you can add

    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    

    this line is how to prevent getting 404 not found errors when using Identity with JWTs. If you are using identity the DefaultChallengeScheme will try to redirect you to a login page, which if non existent will result in getting a 404 not found rather than the wanted 401 unauthorized. by setting the DefaultChallengeScheme to JwtBearerDefaults.AuthenticationScheme on unauthorized it will no longer try to redirect you to a login page

    If you are using Cookie Authentication with JWT authentication in the [Authorize] tag you can specify what authenticationScheme you want. for example

    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    
    0 讨论(0)
  • 2020-12-08 19:02

    This seems to be the behavior you receive when your JWT isn't validated correctly. I had this problem as a result of typing "Bearer: (JWT)" instead of "Bearer (JWT)" in the header

    0 讨论(0)
  • 2020-12-08 19:02

    In case anyone has no luck with answers involving the configuration of IServiceCollection.AddAuthentication or the implementation of Startup.Configure, one thing you may try is to change the configuration of IServiceCollection.AddAuthorization.

    Before making this change, calls to API with a proper token failed with the following log lines.

    [Information] [Microsoft.AspNetCore.Hosting.Diagnostics] Request starting HTTP/1.1 POST http://localhost:5000/api application/json 18
    [Debug] [Microsoft.AspNetCore.Routing.Matching.DfaMatcher] 1 candidate(s) found for the request path '"/api"'
    [Debug] [Microsoft.AspNetCore.Routing.Matching.DfaMatcher] Endpoint '"ApplicationNamespace.Controllers.ApiController.CreateAsync (ApplicationNamespace)"' with route pattern '"Api"' is valid for the request path '"/api"'
    [Debug] [Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware] Request matched endpoint '"ApplicationNamespace.Controllers.ApiController.CreateAsync (ApplicationNamespace)"'
    [Debug] [Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler] AuthenticationScheme: "Identity.Application" was not authenticated.
    [Debug] [Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler] AuthenticationScheme: "Identity.Application" was not authenticated.
    [Information] [Microsoft.AspNetCore.Authorization.DefaultAuthorizationService] Authorization failed.
    [Information] [Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler] Successfully validated the token.
    [Information] [Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler] AuthenticationScheme: "Bearer" was challenged.
    [Information] [Serilog.AspNetCore.RequestLoggingMiddleware] HTTP "POST" "/api" responded 401 in 4.6311 ms
    

    In Startup.ConfigureServices, it works for me once I applied a default policy with authentication scheme specified.

    services.AddAuthorization(opt =>
      {
        var builder = new AuthorizationPolicyBuilder();
        builder.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
        builder.RequireAuthenticatedUser();
        opt.DefaultPolicy = builder.Build();
      });
    
    0 讨论(0)
  • 2020-12-08 19:03

    Check signing key encoding in your token provider it can be for example UTF8 not ASCII.

    0 讨论(0)
  • 2020-12-08 19:08

    For anyone using .NET Core 3.1, this is how it works:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseCors("AllowOrigin");
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    
    0 讨论(0)
提交回复
热议问题