Use multiple JWT Bearer Authentication

C#Firebase Authenticationasp.net Core-MvcJwtasp.net Core-2.0

C# Problem Overview


Is it possible to support multiple JWT Token issuers in ASP.NET Core 2? I want to provide an API for external service and I need to use two sources of JWT tokens - Firebase and custom JWT token issuers. In ASP.NET core I can set the JWT authentication for Bearer auth scheme, but only for one Authority:

  services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/my-firebase-project"
            options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "my-firebase-project"
                    ValidateAudience = true,
                    ValidAudience = "my-firebase-project"
                    ValidateLifetime = true
                };
        }

I can have multiple issuers and audiences, but I can't set several Authorities.

C# Solutions


Solution 1 - C#

You can totally achieve what you want:

services
    .AddAuthentication()
    .AddJwtBearer("Firebase", options =>
    {
        options.Authority = "https://securetoken.google.com/my-firebase-project"
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "my-firebase-project"
            ValidateAudience = true,
            ValidAudience = "my-firebase-project"
            ValidateLifetime = true
        };
    })
    .AddJwtBearer("Custom", options =>
    {
        // Configuration for your custom
        // JWT tokens here
    });

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();
    });

Let's go through the differences between your code and that one.

AddAuthentication has no parameter

If you set a default authentication scheme, then on every single request the authentication middleware will try to run the authentication handler associated with the default authentication scheme. Since we now have two possible authentication schemes, there's no point in running one of them.

Use another overload of AddJwtBearer

Every single AddXXX method to add an authentication has several overloads:

  • One where the default authentication scheme associated with the authentication method is used, as you can see here for cookies authentication
  • One where you pass, in addition to the configuration of the options, the name of the authentication scheme, as on this overload

Now, because you use the same authentication method twice but authentication schemes must be unique, you need to use the second overload.

Update the default policy

Since the requests won't be authenticated automatically anymore, putting [Authorize] attributes on some actions will result in the requests being rejected and an HTTP 401 will be issued.

Since that's not what we want because we want to give the authentication handlers a chance to authenticate the request, we change the default policy of the authorization system by indicating both the Firebase and Custom authentication schemes should be tried to authenticate the request.

That doesn't prevent you from being more restrictive on some actions; the [Authorize] attribute has an AuthenticationSchemes property that allows you to override which authentication schemes are valid.

If you have more complex scenarios, you can make use of policy-based authorization. I find the official documentation is great.

Let's imagine some actions are only available to JWT tokens issued by Firebase and must have a claim with a specific value; you could do it this way:

// Authentication code omitted for brevity

services
    .AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase", "Custom")
            .Build();

        options.AddPolicy("FirebaseAdministrators", new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .AddAuthenticationSchemes("Firebase")
            .RequireClaim("role", "admin")
            .Build());
    });

You could then use [Authorize(Policy = "FirebaseAdministrators")] on some actions.

A final point to note: If you are catching AuthenticationFailed events and using anything but the first AddJwtBearer policy, you may see IDX10501: Signature validation failed. Unable to match key... This is caused by the system checking each AddJwtBearer in turn until it gets a match. The error can usually be ignored.

Solution 2 - C#

This is an extension of Mickaël Derriey's answer.

Our app has a custom authorization requirement that we resolve from an internal source. We were using Auth0 but are switching to Microsoft Account authentication using OpenID. Here is the slightly edited code from our ASP.Net Core 2.1 Startup. For future readers, this works as of this writing for the versions specified. The caller uses the id_token from OpenID on incoming requests passed as a Bearer token. Hope it helps someone else trying to do an identity authority conversion as much as this question and answer helped me.

const string Auth0 = nameof(Auth0);
const string MsaOpenId = nameof(MsaOpenId);

string domain = "https://myAuth0App.auth0.com/";
services.AddAuthentication()
        .AddJwtBearer(Auth0, options =>
            {
                options.Authority = domain;
                options.Audience = "https://myAuth0Audience.com";
            })
        .AddJwtBearer(MsaOpenId, options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateAudience = true,
                    ValidAudience = "00000000-0000-0000-0000-000000000000",

                    ValidateIssuer = true,
                    ValidIssuer = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",

                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidateLifetime = true,
                    RequireSignedTokens = true,
                    ClockSkew = TimeSpan.FromMinutes(10),
                };
                options.MetadataAddress = "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0/.well-known/openid-configuration";
            }
        );

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes( Auth0, MsaOpenId )
        .Build();

    var approvedPolicyBuilder =  new AuthorizationPolicyBuilder()
           .RequireAuthenticatedUser()
           .AddAuthenticationSchemes(Auth0, MsaOpenId)
           ;

    approvedPolicyBuilder.Requirements.Add(new HasApprovedRequirement(domain));

    options.AddPolicy("approved", approvedPolicyBuilder.Build());
});

Solution 3 - C#

The solution to your question, is available in following blog post https://oliviervaillancourt.com/posts/Fixing-IDX10501-MultipleAuthScheme

Basically the solutions exists of overriding the regular JWTBearer handler with you own generic handler that can check through the JWTBearerConfig if the issuer in the cfg is the same to the isseur in your token.

The blog post suggests to use seperate handlers for each scheme, that doesn't seem to be needed, a generic class JWTAuthenticationHandler that overrides the HandleAuthenticateAsync method seems to suffice!

Code wise you could implement your startup like this:

 //Using multiple schemes can cause issues when validating the issuesSigningKey therefore we need to implement seperate handlers for each scheme! => cfr: https://oliviervaillancourt.com/posts/Fixing-IDX10501-MultipleAuthScheme
        services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
        services.AddAuthentication()
        //Set the authenticationScheme by using the identityServer helper methods (we are using a Bearer token)
        .AddScheme<JwtBearerOptions, JWTAuthenticationHandler>(IdentityServerAuthenticationDefaults.AuthenticationScheme, options =>
        {
            //TO DO Get the origin url's from configuration file, instead of setting all url's here 
            options.Authority = _identityServerSettings.Authority;
            options.Audience = _identityServerSettings.Audience;

            options.Events = new JwtBearerEvents
            {
                OnChallenge = context =>
                {
                    return Task.CompletedTask;
                },
                //When using multiple JwtBearer schemes we can run into "OnAuthenticationFailed" for instance when logging in via IdentityServer the AuthenticationHandler will still check in these events, this can be ignored...
                //Cfr => https://stackoverflow.com/questions/49694383/use-multiple-jwt-bearer-authentication
                //If you are catching AuthenticationFailed events and using anything but the first AddJwtBearer policy, you may see IDX10501: Signature validation failed.Unable to match key... This is caused by the system checking each AddJwtBearer in turn until it gets a match. The error can usually be ignored.
                //We managed to fix this issue by adding seperate AuthenticationHandlers for each type of bearer token... cfr: https://oliviervaillancourt.com/posts/Fixing-IDX10501-MultipleAuthScheme
                OnAuthenticationFailed = context =>
                {
                    return Task.CompletedTask;
                },
                OnMessageReceived = context =>
                {
                    return Task.CompletedTask;
                },
                OnForbidden = context =>
                {
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    return Task.CompletedTask;
                }

            };
        })
        //Set the authentication scheme for the AzureAd integration (we are using a bearer token)
        .AddScheme<JwtBearerOptions, JWTAuthenticationHandler>("AzureAD", "AzureAD", options =>
         {
            options.Audience = _azureAdSettings.Audience;   //ClientId 
            options.Authority = _azureAdSettings.Authority; //"https://login.microsoftonline.com/{tenantId}/v2.0/"

            options.TokenValidationParameters = new TokenValidationParameters
             {
                //Set built in claimTypes => Role
                RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
             };

             options.Events = new JwtBearerEvents
             {
                 OnChallenge = context =>
                 {
                     return Task.CompletedTask;
                 },
                 //When using multiple JwtBearer schemes we can run into "OnAuthenticationFailed" for instance when logging in via IdentityServer the AuthenticationHandler will still check in these events, this can be ignored...
                 //Cfr => https://stackoverflow.com/questions/49694383/use-multiple-jwt-bearer-authentication
                 //A final point to note: If you are catching AuthenticationFailed events and using anything but the first AddJwtBearer policy, you may see IDX10501: Signature validation failed.Unable to match key... This is caused by the system checking each AddJwtBearer in turn until it gets a match. The error can usually be ignored.
                 //We managed to fix this issue by adding seperate AuthenticationHandlers for each type of bearer token... cfr: https://oliviervaillancourt.com/posts/Fixing-IDX10501-MultipleAuthScheme
                 OnAuthenticationFailed = context =>
                 {
                     return Task.CompletedTask;
                 },
                 OnMessageReceived = context =>
                 {
                     return Task.CompletedTask;
                 },
                 OnForbidden = context =>
                 {
                     return Task.CompletedTask;
                 },
                 OnTokenValidated = context =>
                 {
                     return Task.CompletedTask;
                 }
                 
             };
         });
    }

The JWTAuthenticationHandlerClass can look like this

  using Microsoft.AspNetCore.Authentication;
  using Microsoft.AspNetCore.Authentication.JwtBearer;
  using Microsoft.Extensions.Logging;
  using Microsoft.Extensions.Options;
  using System;
  using System.IdentityModel.Tokens.Jwt;
  using System.Text.Encodings.Web;
  using System.Threading.Tasks;

  namespace WebAPI.Auth
  {
    public class JWTAuthenticationHandler: JwtBearerHandler
    {
    public JWTAuthenticationHandler(IOptionsMonitor<JwtBearerOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    { }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        //Fetch OIDC configuration for the IDP we are handling
        var authorityConfig = await this.Options.ConfigurationManager.GetConfigurationAsync(this.Context.RequestAborted);
        //Determine the issuer from the configuration
        var authorityIssuer = authorityConfig.Issuer;

        var jwtToken = this.ReadTokenFromHeader();
        var jwtHandler = new JwtSecurityTokenHandler();

        //Check if we can read the token as a valid JWT, if not let the JwtBearerHandler do it's thing...
        if (jwtHandler.CanReadToken(jwtToken))
        {
            //Read the token and determine if the issuer in config is the same as the one in the token, if this is true we know we want to let the JwtBearerHandler continue, if not we skip and return noResult
            //This way the next IDP configuration will pass here until we find a matching issuer and then we know that is the IDP we are dealing with
            var token = jwtHandler.ReadJwtToken(jwtToken);
            if (string.Equals(token.Issuer, authorityIssuer, StringComparison.OrdinalIgnoreCase))
            {
                return await base.HandleAuthenticateAsync();
            }
            else
            {
                // return NoResult since the issuer in cfg did not match the one in the token, so no need to proceed to tokenValidation
                this.Logger.LogDebug($"Skipping jwt token validation because token issuer was {token.Issuer} but the authority issuer is: {authorityIssuer}");
                return AuthenticateResult.NoResult();
            }
        }

        return await base.HandleAuthenticateAsync();
    }

    //Fetch the bearer token from the authorization header on the request!
    private string ReadTokenFromHeader()
    {
        string token = null;

        string authorization = Request.Headers["Authorization"];

        //If we don't find the authorization header return null
        if (string.IsNullOrEmpty(authorization))
        {
            return null;
        }

        //get the token from the auth header
        if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
        {
            token = authorization.Substring("Bearer ".Length).Trim();
        }

        return token;
    }
}

}

Solution 4 - C#

One thing that was missing in Mickael's answer is that scheme needs to be specified in Authorize attribute (If you want to use authorization)

[Authorize(AuthenticationSchemes = "Firebase,Custom", Policy ="FirebaseAdministrators")]

Without AuthenticationSchemes provided, and AddAuthentication() has no parameter, NetCore fails to Authenticate and Request.HttpContext.User.Identity.IsAuthenticated is set to false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaneView Question on Stackoverflow
Solution 1 - C#Mickaël DerrieyView Answer on Stackoverflow
Solution 2 - C#No Refunds No ReturnsView Answer on Stackoverflow
Solution 3 - C#PieterView Answer on Stackoverflow
Solution 4 - C#hurray yarruhView Answer on Stackoverflow