Dotnet core 2.0 Use Identity with JwtBearer Authentication

3.2k views Asked by At

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,

2

There are 2 answers

2
Jaco van Rensburg On BEST ANSWER

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;
})
1
LaylaCodesIt On

In answer to the question:

Do you know how to stop default redirection to login page during an unauthorized access?

I found this blog post by PioneerCode for dotnet core 1 which may be helpful.

This is how I implemented it and it worked:

services.ConfigureApplicationCookie(options => { options.LoginPath = "/api/login";
    options.Events = new CookieAuthenticationEvents
    {
      OnRedirectToLogin = ctx =>
      {
        if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
        {
          ctx.Response.StatusCode = 401;
          return Task.FromResult<object>(null);
        }

        ctx.Response.Redirect(ctx.RedirectUri);
        return Task.FromResult<object>(null);
      }
    };
  });