public static ClaimsPrincipal AuthenticateIdToken(HttpApplication application, string id_token) { var config = OpenIdConfiguration.Current; var handler = new JwtSecurityTokenHandler(); handler.CertificateValidator = X509CertificateValidator.None; if (!handler.CanReadToken(id_token)) { throw new InvalidOperationException("No SecurityTokenHandler can authenticate this id_token!"); } var parameters = new TokenValidationParameters(); parameters.AllowedAudience = AADClientId; // this is just for Saml // paramaters.AudienceUriMode = AudienceUriMode.Always; parameters.ValidateIssuer = false; var tokens = new List<SecurityToken>(); foreach (var key in config.IssuerKeys.Keys) { tokens.AddRange(key.GetSecurityTokens()); } parameters.SigningTokens = tokens; // validate var principal = (ClaimsPrincipal)handler.ValidateToken(id_token, parameters); // verify nonce VerifyNonce(principal.FindFirst(NonceClaimType).Value); return principal; }
public static string GetCurrentUserID(string token) { JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); var canReadToken = handler.CanReadToken(token); if (canReadToken) { var tempToken = handler.ReadToken(token) as JwtSecurityToken; ///TODO: this could be used to HTTP request the metadata... //issuer = tt.Issuer; var claims = new List<Claim>(); foreach (var claim in tempToken.Claims) { claims.Add(claim); } var principal = new ClaimsPrincipal(new ClaimsIdentity(claims)); Thread.CurrentPrincipal = principal; } return GetCurrentUserID(); ///TODO: wire up real token validate... /// /* TokenValidationParameters validationParameters = new TokenValidationParameters() { ValidAudience = ConfigurationManager.AppSettings["ida:Audience"], ValidateIssuer = false, ValidateActor = false, ValidateIssuerSigningKey = false, CertificateValidator = X509CertificateValidator.None }; SecurityToken jwtToken = null; var p = handler.ValidateToken(token, validationParameters, out jwtToken); */ }
private IPrincipal ValidateJWT(string jwt) { var handler = new JwtSecurityTokenHandler { CertificateValidator = X509CertificateValidator.None }; if (!handler.CanReadToken(jwt)) { return null; } var parameters = new TokenValidationParameters { ValidAudience = GetValidAudiance(), ValidateIssuer = false, IssuerSigningTokens = OpenIdConfiguration.GetIssuerSigningKeys(jwt) }; try { var user = handler.ValidateToken(jwt, parameters); var upnClaim = user.Claims.Where(c => c.Type == upnClaimType).Select(c => c.Value).FirstOrDefault(); var emailClaim = user.Claims.Where(c => c.Type == emailClaimType).Select(c => c.Value).FirstOrDefault(); var nameClaim = user.Claims.Where(c => c.Type == nameClaimType).Select(c => c.Value).FirstOrDefault(); var issuerClaim = user.Claims.Where(c => c.Type == issuerClaimType).Select(c => c.Value).FirstOrDefault(); var puidClaim = user.Claims.Where(c => c.Type == puidClaimType ).Select(c => c.Value).FirstOrDefault(); var altSecId = user.Claims.Where(c => c.Type == altSecIdClaimType).Select(c => c.Value).FirstOrDefault(); var principal = new TryWebsitesPrincipal(new TryWebsitesIdentity(upnClaim ?? emailClaim ?? user.Identity.Name, altSecId ?? puidClaim, GetIssuerName(altSecId ?? puidClaim))); return principal; } catch (Exception e) { //failed validating SimpleTrace.Diagnostics.Error(e, "Error reading claims {jwt}", jwt); } return null; }
public void GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery() { // // The Client ID is used by the application to uniquely identify itself to Azure AD. // The App Key is a credential used by the application to authenticate to Azure AD. // The Tenant is the name of the Azure AD tenant in which this application is registered. // The AAD Instance is the instance of Azure, for example public Azure or Azure China. // The Authority is the sign-in URL of the tenant. // string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; string tenant = ConfigurationManager.AppSettings["ida:Tenant"]; string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; string appKey = ConfigurationManager.AppSettings["ida:AppKey"]; string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); // // To authenticate to the To Do list service, the client needs to know the service's App ID URI. // To contact the To Do list service we need it's URL as well. // string appResourceId = ConfigurationManager.AppSettings["app:AppResourceId"]; IContentKey contentKey = null; IContentKeyAuthorizationPolicy contentKeyAuthorizationPolicy = null; IContentKeyAuthorizationPolicyOption policyOption = null; var authContext = new AuthenticationContext(authority); var clientCredential = new ClientCredential(clientId, appKey); try { byte[] expectedKey = null; contentKey = CreateTestKey(_mediaContext, ContentKeyType.EnvelopeEncryption, out expectedKey, "GetHlsKeyDeliveryUrlAndFetchKeyWithADJWTAuthUsingADOpenConnectDiscovery"+Guid.NewGuid().ToString()); TokenRestrictionTemplate tokenRestrictionTemplate = new TokenRestrictionTemplate(TokenType.JWT); tokenRestrictionTemplate.OpenIdConnectDiscoveryDocument = new OpenIdConnectDiscoveryDocument("https://login.windows.net/common/.well-known/openid-configuration"); var result = authContext.AcquireToken(appResourceId, clientCredential); string jwtTokenString = result.AccessToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); Assert.IsTrue(handler.CanReadToken(jwtTokenString)); JwtSecurityToken token = handler.ReadToken(jwtTokenString) as JwtSecurityToken; Assert.IsNotNull(token); tokenRestrictionTemplate.Audience = token.Audiences.First(); tokenRestrictionTemplate.Issuer = token.Issuer; string optionName = "GetHlsKeyDeliveryUrlAndFetchKeyWithJWTAuthentication"; string requirements = TokenRestrictionTemplateSerializer.Serialize(tokenRestrictionTemplate); policyOption = ContentKeyAuthorizationPolicyOptionTests.CreateOption(_mediaContext, optionName, ContentKeyDeliveryType.BaselineHttp, requirements, null, ContentKeyRestrictionType.TokenRestricted); List<IContentKeyAuthorizationPolicyOption> options = new List<IContentKeyAuthorizationPolicyOption> { policyOption }; contentKeyAuthorizationPolicy = CreateTestPolicy(_mediaContext, String.Empty, options, ref contentKey); Uri keyDeliveryServiceUri = contentKey.GetKeyDeliveryUrl(ContentKeyDeliveryType.BaselineHttp); Assert.IsNotNull(keyDeliveryServiceUri); // Enable once all accounts are enabled for per customer Key Delivery Urls //Assert.IsTrue(keyDeliveryServiceUri.Host.StartsWith(_mediaContext.Credentials.ClientId)); KeyDeliveryServiceClient keyClient = new KeyDeliveryServiceClient(RetryPolicy.DefaultFixed); byte[] key = keyClient.AcquireHlsKeyWithBearerHeader(keyDeliveryServiceUri, jwtTokenString); string expectedString = GetString(expectedKey); string fetchedString = GetString(key); Assert.AreEqual(expectedString, fetchedString); } finally { CleanupKeyAndPolicy(contentKey, contentKeyAuthorizationPolicy, policyOption); } }
public void JwtSecurityTokenHandler_ReadToken() { JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); ExpectedException expectedException = ExpectedException.ArgumentOutOfRangeException(); try { handler.MaximumTokenSizeInBytes = 0; expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } Assert.IsFalse(handler.CanReadToken("1"), string.Format("Expected JWTSecurityTokenHandler.CanReadToken to be false")); expectedException = ExpectedException.ArgumentException(substringExpected: "IDX10708:"); try { handler.ReadToken("1"); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } }
private bool RunCanReadStringVariation(string securityToken, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { bool retVal = false; try { retVal = tokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
private bool RunCanReadXmlVariation(XmlReader reader, JwtSecurityTokenHandler tokenHandler,ExpectedException expectedException) { bool retVal = false; try { retVal = tokenHandler.CanReadToken(reader); expectedException.ProcessNoException(); } catch(Exception ex) { expectedException.ProcessException(ex); } return retVal; }