Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 747
Wijitha Avatar asked Aug 27 '17 12:08

Wijitha


2 Answers

If I understand correctly from the MS site

https://docs.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;
})
like image 67
Jaco van Rensburg Avatar answered Sep 27 '22 21:09

Jaco van Rensburg


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);
      }
    };
  });
like image 25
LaylaCodesIt Avatar answered Sep 27 '22 21:09

LaylaCodesIt