Skip to content

Instantly share code, notes, and snippets.

@JamesRandall
Created June 16, 2018 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesRandall/e83f72f98bde2f6ff973e6ecb81199c8 to your computer and use it in GitHub Desktop.
Save JamesRandall/e83f72f98bde2f6ff973e6ecb81199c8 to your computer and use it in GitHub Desktop.
Sample ITokenValidator implementation for FunctionMonkey
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