Dotnet core 2.0 authentication multiple schemas identity cookies and jwt

Asp.Net Core 2.0 definitely support multiple authentication schemes.
Rather than a hacking with authenticate middleware, you can try to specify the schema in Authorize attribute:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

I gave a try and it worked fine. Assuming you have added both Identity and JWT as below:

services.AddIdentity<ApplicationUser, ApplicationRole>()
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

Since AddIdentity() already set cookie authentication as the default schema, we have to specify schema in Authorize attribute of controllers. For now, I have no idea how to overwrite the default schema set by AddIdentity(), or maybe we’d better not to do that.

A work around is to compose a new class (you can call it JwtAuthorize) that derives from Authorize and have Bearer as the default schema, so you don’t have to specify it every time.

UPDATE

Found the way to override Identity default authentication scheme!

Instead of below line:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

Use below overload to set default schema:

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

UPDATE 2
As mentioned in comments, you can enable both Identity and JWT auth by join them together.

[Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]

Leave a Comment