I have two different jwt auth tokens from two different providers my api accepts, setup as so:
services.AddAuthentication()
.AddJwtBearer("auth provider1", options =>
{
options.Audience = authSettings.Audience1;
options.Authority = authSettings.Authority1;
options.ClaimsIssuer = authSettings.Issuer1;
})
.AddJwtBearer("auth provider2", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.FromMinutes(5),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authSettings.SymmetricKey)),
RequireSignedTokens = true,
RequireExpirationTime = true,
ValidateLifetime = true,
ValidateAudience = true,
ValidAudience = authSettings.Audience2,
ValidateIssuer = true,
ValidIssuer = authSettings.Issuer2
};
});
These auth providers have access to different APIs so when a access token attempts to access a API it's not allowed to I will throw a 403. I accomplish this with the following policy setup
services.AddAuthorization(options =>
{
// Blocks auth provider 2 tokens by returning 403 because it does not have claim only present in tokens from auth provider 1
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.RequireClaim(Constants.CLAIM_ONLY_IN_AUTH_1)
.AddAuthenticationSchemes("auth provider1", "auth provider2")
.Build();
// Accepts both auth provider tokens
options.AddPolicy("accept both auth1 and auth2 policy", new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.AddAuthenticationSchemes("auth provider1", "auth provider2")
.Build());
});
I am running into the following exception when I use either of these policies because I believe the pipeline tries to validate the auth token passed in on both authentication schemes.
IDX10501: Signature validation failed. Unable to match 'kid':
The exception doesn't bubble up and terminate requests it just adds lots of noise to my logging, has anyone encountered this exception when using multiple authentication schemes on one policy?
On the OnAuthenticationFailed > under one of the jwtOptions.Events, add a condition if it's authenticated then complete the task and don't show the error. Sometimes the user is authenticated already but the error from one provider prevents the proper response
if (arg.HttpContext.User.Identity.IsAuthenticated)
{
return Task.CompletedTask;
}
If you encounter problems with authenticating for both jwt provider, you can try other solutions here: .net core 2.2 multiple bearer token authentication schemes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With