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

后端 未结 11 1476
暗喜
暗喜 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 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)]
    

提交回复
热议问题