Created
June 16, 2018 07:49
-
-
Save JamesRandall/e83f72f98bde2f6ff973e6ecb81199c8 to your computer and use it in GitHub Desktop.
Sample ITokenValidator implementation for FunctionMonkey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BearerTokenValidator : ITokenValidator | |
{ | |
private static readonly IConfigurationManager<OpenIdConnectConfiguration> ConfigurationManager; | |
static BearerTokenValidator() | |
{ | |
string domain = Environment.GetEnvironmentVariable("domain"); | |
string wellKnownEndpoint = $"https://{domain}/.well-known/openid-configuration"; | |
var documentRetriever = new HttpDocumentRetriever { RequireHttps = wellKnownEndpoint.StartsWith("https://") }; | |
ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>( | |
wellKnownEndpoint, | |
new OpenIdConnectConfigurationRetriever(), | |
documentRetriever | |
); | |
} | |
public async Task<ClaimsPrincipal> ValidateAsync(string authorizationHeader) | |
{ | |
if (!authorizationHeader.StartsWith("Bearer ")) | |
return null; | |
string bearerToken = authorizationHeader.Substring("Bearer ".Length); | |
var config = await ConfigurationManager.GetConfigurationAsync(CancellationToken.None); | |
var audience = Environment.GetEnvironmentVariable("audience"); | |
var validationParameter = new TokenValidationParameters() | |
{ | |
RequireSignedTokens = true, | |
ValidAudience = audience, | |
ValidateAudience = true, | |
ValidIssuer = config.Issuer, | |
ValidateIssuer = true, | |
ValidateIssuerSigningKey = true, | |
ValidateLifetime = true, | |
IssuerSigningKeys = config.SigningKeys | |
}; | |
ClaimsPrincipal result = null; | |
var tries = 0; | |
while (result == null && tries <= 1) | |
{ | |
try | |
{ | |
var handler = new JwtSecurityTokenHandler(); | |
result = handler.ValidateToken(bearerToken, validationParameter, out SecurityToken _); | |
} | |
catch (SecurityTokenSignatureKeyNotFoundException) | |
{ | |
// This exception is thrown if the signature key of the JWT could not be found. | |
// This could be the case when the issuer changed its signing keys, so we trigger a | |
// refresh and retry validation. | |
ConfigurationManager.RequestRefresh(); | |
tries++; | |
} | |
catch (SecurityTokenException) | |
{ | |
return null; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment