The following code decrypts the AAD token from the Azure App Service HTTP header and populates the HttpContext.User request. This is rude because you want to cache the configuration, rather than looking for it for every request:
OpenIdConnectConfigurationRetriever r = new OpenIdConnectConfigurationRetriever(); ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(options.Endpoint, r); OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync(); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKeys = config.SigningKeys.ToList(), ValidateIssuer = true, ValidIssuer = config.Issuer, ValidateAudience = true, ValidAudience = options.Audience, ValidateLifetime = true, ClockSkew = new TimeSpan(0, 0, 10) }; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); ClaimsPrincipal principal = null; SecurityToken validToken = null; string token = context.Request.Headers["X-MS-TOKEN-AAD-ID-TOKEN"]; if (!String.IsNullOrWhiteSpace(token)) { principal = handler.ValidateToken(token, tokenValidationParameters, out validToken); var validJwt = validToken as JwtSecurityToken; if (validJwt == null) { throw new ArgumentException("Invalid JWT"); } if (principal != null) { context.User.AddIdentities(principal.Identities); } }
It works only for Azure AD. To support other ID providers (Facebook, Twitter, etc.), you will need to find the appropriate headers and figure out how to parse the provider tokens. However, these should only be variations on a given topic.
Rhysk source share