Created
March 18, 2020 01:25
-
-
Save AlbertoDePena/daaa6426abb9baf4f0ec50b6f2ce4198 to your computer and use it in GitHub Desktop.
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
// Microsoft.IdentityModel.Protocols.OpenIdConnect | |
// System.IdentityModel.Tokens.Jwt | |
/// <summary> | |
/// Token validator | |
/// </summary> | |
public class TokenValidator | |
{ | |
private readonly TokenValidationParameters _tokenValidationParameters; | |
/// <summary> | |
/// Validate authenticated user/application using open ID connection configuration | |
/// </summary> | |
/// <param name="authority">The authority</param> | |
/// <param name="clientId">The client ID</param> | |
public TokenValidator(string authority, string clientId) | |
{ | |
if (string.IsNullOrWhiteSpace(authority)) throw new ArgumentNullException(nameof(authority)); | |
if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException(nameof(clientId)); | |
var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(authority + "/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever()); | |
var configuration = AsyncHelper.RunSync(async () => await configurationManager.GetConfigurationAsync(CancellationToken.None)); | |
_tokenValidationParameters = | |
new TokenValidationParameters | |
{ | |
ValidAudience = clientId, | |
ValidIssuer = configuration.Issuer, | |
IssuerSigningKeys = configuration.SigningKeys, | |
ValidateIssuerSigningKey = true, | |
}; | |
} | |
/// <summary> | |
/// Validate token | |
/// </summary> | |
/// <param name="token"></param> | |
/// <returns></returns> | |
public TokenValidationResult ValidateToken(string token) | |
{ | |
var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(token, _tokenValidationParameters, out SecurityToken securityToken); | |
return new TokenValidationResult(claimsPrincipal, securityToken); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment