Reputation: 587
I have a scenario where there are many separate clients connecting via JWT token.
p.s. Each client has a different secret
I can do this on a per app basis
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AllowedAudiences = new[] { audience },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
},
Provider = new CookieOAuthBearerProvider("authCookie")
});
But this method will not work on a per request basis....
Upvotes: 1
Views: 3111
Reputation: 27367
This is a snippet from what we're currently using (connecting to AzureAD).
You'll need to implement GetSigningCertificates
which returns IEnumerable<X509SecurityToken>
to validate the JWT is properly signed.
internal static ClaimsPrincipal GetClaimPrincipalFromToken(string jwtSecurityHeader)
{
var jwtSecurityHandler = new JwtSecurityTokenHandler();
var signingCertificates = GetSigningCertificates(ConfigHelper.FederationMetadataDocument);
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidAudience = ConfigHelper.AppIdURI,
ValidIssuer = ConfigHelper.Issuer,
LifetimeValidator =
(before, expires, token, parameters) =>
{
//Don't allow not-yet-active tokens
if (before.HasValue && before.Value > DateTime.Now)
return false;
//If expiration has a date, add 2 days to it
if (expires.HasValue)
return expires.Value.AddDays(2) > DateTime.Now;
//Otherwise the token is valid
return true;
},
ValidateLifetime = true,
IssuerSigningTokens = signingCertificates,
};
var headerParts = jwtSecurityHeader.Split(' ');
if (headerParts.Length != 2 || headerParts[0] != "Bearer")
throw new AuthorizationException(HttpStatusCode.Forbidden, "Invalid token type");
var jwtSecurityToken = headerParts[1];
SecurityToken jwtToken;
var claimsPrincipal = jwtSecurityHandler.ValidateToken(jwtSecurityToken, tokenValidationParameters, out jwtToken);
return claimsPrincipal;
}
You'll need to tweak it a bit for your application, but this should get you most of the way there. Note that this code is parsing a {HeaderType} {Token}
format (for example Bearer {token}
). If you're simplying parsing the {Token}
, you need to remove the .Split(' ')
Upvotes: 2