Default Identity clashes with JWT

Viewed 79

I have an ASP.NET Core 3.1 website that uses Identity for authentication on the actual customer-facing website. It also has an API backend that I want to secure with JWT for external user access.

However, using both authentication systems together is causing a problem. Setting the default authentication schemes to IdentityConstants.ApplicationScheme (or empty) causes JWT to fail authentication by routing API calls through the Identity scheme. Likewise, setting the schemes to JwtBearerDefaults.AuthenticationScheme causes the main site to fail by routing calls through the JWT scheme.

How can I separate the two so that anything routing through "/api" uses the JWT scheme and all other calls are handled by the default Identity scheme?

Here's part of the setup so far: startup.cs

public void ConfigureServices(IServiceCollection services)
{
...
   services.AddDefaultIdentity<IdentityUser>(options => { 

      options.SignIn.RequireConfirmedAccount = true;
      options.SignIn.RequireConfirmedEmail = false;

      options.Password.RequireDigit = true;
      options.Password.RequiredLength = 8;
      options.Password.RequireLowercase = true;
      options.Password.RequireUppercase = true;
      options.Password.RequireNonAlphanumeric = true;

      options.Lockout.MaxFailedAccessAttempts = 5;

      options.User.RequireUniqueEmail = true;
                
  }).AddEntityFrameworkStores<ApplicationDbContext>();

...

   services.AddAuthentication(x =>
   {
      // ** Playing with these settings **
      //x.DefaultScheme = IdentityConstants.ApplicationScheme;
      ////x.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
      ////x.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
      //x.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
      //x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
      //x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

  }).AddJwtBearer(x =>
  {                
      x.RequireHttpsMetadata = true;
      x.SaveToken = true;
      x.TokenValidationParameters = new TokenValidationParameters
      {
          ValidateIssuerSigningKey = false,
          IssuerSigningKey = new SymmetricSecurityKey(_SecretKey),
          ValidateIssuer = false,
          ValidateAudience = false,
          ValidateLifetime = true,
          ClockSkew = TimeSpan.Zero
      };
      x.IncludeErrorDetails = true;
  });

Any ideas would be most welcome. I'd prefer not to have to resort to plaintext Licence keys for the API functions.

0 Answers
Related