Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.