Search code examples
asp.netasp.net-web-apiasp.net-identityjwt.net-core-2.0

Dotnet core 2.0 Use Identity with JwtBearer Authentication


In my Asp.Net core web api I was using Identity with Jwt bearer authentication. It was working smoothly without any fuss. Here is the code for that,

ConfigureServices():

 services.AddIdentity<ApplicationUser, IdentityRole<int>>()
            .AddEntityFrameworkStores<DataContext, int>()
            .AddDefaultTokenProviders();

Configure():

  app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer = "localhost:4200",
                    ValidAudience = "localhost:4200",
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings")),
                    ValidateLifetime = true
                }
            });

And today I upgraded to .net core 2.0 and the entire technology stack. From the limited help available out there I have modified code like this..

ConfigureServices()

 services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<DataContext>()
                .AddDefaultTokenProviders();   



services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "localhost:4200";
                    options.Audience = "localhost:4200";
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateLifetime = true,
                    ValidIssuer = "localhost:4200",
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SuperSecretKey_GetThisFromAppSettings"))
                };
            });

Configure()

app.UseAuthentication();

Now the authentication is not working. Looks like its internally configured to use Cookie Authentication.

Has anyone else come across this scenario? Any help on this is really appreciated!

Thanks,


Solution

  • If I understand correctly from the MS site

    https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

    Identity adds cookies and sets the default authentication to the cookie scheme. Try changing your

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

    to

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