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

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?


For Dotnetcore 3.1, I placed app.UseAuthentication() before app.UseAuthorization()


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)]

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();
    });
}