public void SetUp() { Mock<IAuthServiceClient> clientMock = new Mock<IAuthServiceClient>(); clientMock .Setup( x => x.ProvisionAccessTokenAsync( It.IsAny<string>(), It.IsAny<IEnumerable<Scope>>() ) ) .Callback<string, IEnumerable<Scope>>( ( assertion, _ ) => { var tokenHandler = new JwtSecurityTokenHandler(); m_actualAssertion = (JwtSecurityToken)tokenHandler.ReadToken( assertion ); } ) .ReturnsAsync( null ); #pragma warning disable 618 m_publicKeyDataProvider = new InMemoryPublicKeyDataProvider(); #pragma warning restore 618 m_tokenSigner = RsaTokenSignerFactory.Create( m_publicKeyDataProvider ); m_accessTokenProvider = new AccessTokenProvider( m_tokenSigner, clientMock.Object ); }
protected void Page_Load(object sender, EventArgs e) { string spAppToken = TokenHelper.GetContextTokenFromRequest(HttpContext.Current.Request); requestTokenValue.InnerText = spAppToken; SharePointContextToken spToken = ReadToken(spAppToken); requestTokenContents.InnerHtml = spToken.ToString().Replace(",", "<br/>"); string hostWeb = Page.Request["SPHostUrl"]; Uri hostUri = new Uri(hostWeb); string accessToken = TokenHelper.GetAccessToken(spToken,hostUri.Authority).AccessToken; accessTokenValue.InnerText = accessToken; JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); SecurityToken st = tokenHandler.ReadToken(accessToken); accessTokenContents.InnerHtml = st.ToString().Replace(",", "<br/>"); }
public static ClaimsPrincipal ValidateJwtToken(string jwtToken) { var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true }; // Parse JWT from the Base64UrlEncoded wire form (<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>) JwtSecurityToken parsedJwt = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken; TokenValidationParameters validationParams = new TokenValidationParameters() { AllowedAudience = SecurityConstants.TokenAudience, ValidIssuer = SecurityConstants.TokenIssuer, ValidateIssuer = true, SigningToken = new BinarySecretSecurityToken(SecurityConstants.KeyForHmacSha256), }; return tokenHandler.ValidateToken(parsedJwt, validationParams); }
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); */ }
protected void Page_Load(object sender, EventArgs e) { string spAppToken = TokenHelper.GetContextTokenFromRequest(HttpContext.Current.Request); requestTokenValue.InnerText = spAppToken; SharePointContextToken spToken = ReadToken(spAppToken); requestTokenContents.InnerHtml = spToken.ToString().Replace(",", "<br/>"); string hostWeb = Page.Request["SPHostUrl"]; Uri hostUri = new Uri(hostWeb); string accessToken = TokenHelper.GetAccessToken(spToken, hostUri.Authority).AccessToken; accessTokenValue.InnerText = accessToken; JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.JwtSecurityTokenHandler(); SecurityToken st = tokenHandler.ReadToken(accessToken); accessTokenContents.InnerHtml = st.ToString().Replace(",", "<br/>"); }
public static void ParseToken(TokenResponse token) { var handler = new JwtSecurityTokenHandler(); var decodedToken = handler.ReadToken(token.AccessToken) as JwtSecurityToken; Console.WriteLine("--------------------------------"); Console.WriteLine("Access Token:\n{0}\n\n", token.AccessToken); Console.WriteLine("Refresh Token:\n{0}\n\n", token.RefreshToken); Console.WriteLine("Token Type:\n{0}\n", token.TokenType); Console.WriteLine("Issuer:\n{0}\n", decodedToken.Issuer); Console.WriteLine("Audience:\n{0}\n", decodedToken.Audience); Console.WriteLine("Valid:\n{0} - {1}\n", decodedToken.ValidFrom, decodedToken.ValidTo); Console.WriteLine("User:\n{0}\n", decodedToken.Subject); Console.WriteLine("Scopes:"); foreach (var cl in decodedToken.Claims.Where(c => c.Type == "scope")) { Console.Write("{0} ", cl.Value); } Console.WriteLine("\n\n--------------------------------"); }
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 CreateAndValidateTokens_SubClaim() { string issuer = "http://www.GotJWT.com"; string audience = "http://www.contoso.com"; SecurityToken validatedToken; JwtSecurityToken jwt = new JwtSecurityToken( issuer: issuer, audience: audience, claims: ClaimSets.JsonClaims(issuer, issuer), expires: DateTime.UtcNow + TimeSpan.FromHours(1), notBefore: DateTime.UtcNow); JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); string encodedJwt = jwtHandler.WriteToken(jwt); JwtSecurityToken jwtRead = jwtHandler.ReadToken(encodedJwt) as JwtSecurityToken; TokenValidationParameters validationParameters = new TokenValidationParameters() { RequireSignedTokens = false, ValidateAudience = false, ValidIssuer = issuer, }; var cp = jwtHandler.ValidateToken(jwtRead.RawData, validationParameters, out validatedToken); Claim jsonClaim = cp.FindFirst(typeof(Entity).ToString()); Assert.IsNotNull(jsonClaim, string.Format(CultureInfo.InvariantCulture, "Did not find Jsonclaims. Looking for claim of type: '{0}'", typeof(Entity).ToString())); JavaScriptSerializer js = new JavaScriptSerializer(); string jsString = js.Serialize(Entity.Default); Assert.AreEqual(jsString, jsonClaim.Value, string.Format(CultureInfo.InvariantCulture, "Find Jsonclaims of type: '{0}', but they weren't equal.\nExpecting '{1}'.\nReceived '{2}'", typeof(Entity).ToString(), jsString, jsonClaim.Value)); }
public void CreateAndValidateTokens_RoundTripTokens() { SecurityToken validatedToken; JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); //handler.CertificateValidator = X509CertificateValidator.None; foreach (CreateAndValidateParams jwtParams in JwtTestTokens.All) { Console.WriteLine("Validating streaming from JwtSecurityToken and TokenValidationParameters is same for Case: '" + jwtParams.Case); string jwt = handler.WriteToken(jwtParams.CompareTo); ClaimsPrincipal principal = handler.ValidateToken(jwt, jwtParams.TokenValidationParameters, out validatedToken); // create from security descriptor SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor(); tokenDescriptor.SigningCredentials = jwtParams.SigningCredentials; tokenDescriptor.Lifetime = new Lifetime(jwtParams.CompareTo.ValidFrom, jwtParams.CompareTo.ValidTo); tokenDescriptor.Subject = new ClaimsIdentity(jwtParams.Claims); tokenDescriptor.TokenIssuerName = jwtParams.CompareTo.Issuer; foreach(string str in jwtParams.CompareTo.Audiences) { if (!string.IsNullOrWhiteSpace(str)) { tokenDescriptor.AppliesToAddress = str; } } JwtSecurityToken token = handler.CreateToken(tokenDescriptor) as JwtSecurityToken; Assert.IsTrue(IdentityComparer.AreEqual(token, jwtParams.CompareTo), "!IdentityComparer.AreEqual( token, jwtParams.CompareTo )"); // write as xml MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlTextWriter.Create(ms)); handler.WriteToken(writer, jwtParams.CompareTo); writer.Flush(); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(ms, XmlDictionaryReaderQuotas.Max); reader.Read(); token = handler.ReadToken(reader) as JwtSecurityToken; ms.Close(); IdentityComparer.AreEqual(token, jwtParams.CompareTo); } }
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 JwtSecurityToken RunReadStringVariation(string securityToken, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { JwtSecurityToken retVal = null; try { retVal = tokenHandler.ReadToken(securityToken) as JwtSecurityToken; expectedException.ProcessNoException(); } catch (Exception ex) { expectedException.ProcessException(ex); } return retVal; }
private JwtSecurityToken RunReadXmlVariation(XmlReader reader, JwtSecurityTokenHandler tokenHandler, ExpectedException expectedException) { JwtSecurityToken retVal = null; try { retVal = tokenHandler.ReadToken(reader) as JwtSecurityToken;; expectedException.ProcessNoException(); } catch(Exception ex) { expectedException.ProcessException(ex); } return retVal; }
internal static SecurityToken ReadToken(string tokenString) { var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.ReadToken(tokenString); }
private void RunValidationTests( SecurityTokenDescriptor tokenDescriptor, SecurityToken securityToken, SecurityKey key, int iterations, bool display = true ) { // Create jwts using wif // Create Saml2 tokens // Create Saml tokens DateTime started; string validating = "Validating, signed: '{0}', '{1}' Tokens. Time: '{2}'"; SetReturnSecurityTokenResolver str = new Test.SetReturnSecurityTokenResolver( securityToken, key ); SecurityTokenHandlerConfiguration tokenHandlerConfiguration = new SecurityTokenHandlerConfiguration() { IssuerTokenResolver = str, SaveBootstrapContext = true, CertificateValidator = AlwaysSucceedCertificateValidator.New, AudienceRestriction = new AudienceRestriction( AudienceUriMode.Never ), IssuerNameRegistry = new SetNameIssuerNameRegistry( Issuers.GotJwt ), }; Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler(); Saml2SecurityToken token = samlTokenHandler.CreateToken( tokenDescriptor ) as Saml2SecurityToken; StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); samlTokenHandler.WriteToken( writer, token ); writer.Flush(); writer.Close(); string tokenXml = sb.ToString(); samlTokenHandler.Configuration = tokenHandlerConfiguration; started = DateTime.UtcNow; for ( int i = 0; i < iterations; i++ ) { StringReader sr = new StringReader( tokenXml ); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader( XmlReader.Create( sr ) ); reader.MoveToContent(); SecurityToken saml2Token = samlTokenHandler.ReadToken( reader ); samlTokenHandler.ValidateToken( saml2Token ); } if ( display ) { Console.WriteLine( string.Format( validating, "Saml2SecurityTokenHandler", iterations, DateTime.UtcNow - started ) ); } JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwt = jwtTokenHandler.CreateToken( tokenDescriptor ) as JwtSecurityToken; jwtTokenHandler.Configuration = tokenHandlerConfiguration; started = DateTime.UtcNow; for ( int i = 0; i < iterations; i++ ) { jwtTokenHandler.ValidateToken( jwt.RawData ); } if ( display ) { Console.WriteLine( string.Format( validating, "JwtSecurityTokenHandle - ValidateToken( jwt.RawData )", iterations, DateTime.UtcNow - started ) ); } jwt = jwtTokenHandler.CreateToken( tokenDescriptor ) as JwtSecurityToken; sb = new StringBuilder(); writer = XmlWriter.Create(sb); jwtTokenHandler.WriteToken( writer, jwt ); writer.Flush(); writer.Close(); tokenXml = sb.ToString(); started = DateTime.UtcNow; for ( int i = 0; i<iterations; i++ ) { StringReader sr = new StringReader( tokenXml ); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader( XmlReader.Create( sr ) ); reader.MoveToContent(); SecurityToken jwtToken = jwtTokenHandler.ReadToken( reader ); jwtTokenHandler.ValidateToken( jwtToken ); } if ( display ) { Console.WriteLine( string.Format( validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken )", iterations, DateTime.UtcNow - started ) ); } started = DateTime.UtcNow; for ( int i = 0; i < iterations; i++ ) { StringReader sr = new StringReader( tokenXml ); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader( XmlReader.Create( sr ) ); reader.MoveToContent(); JwtSecurityToken jwtToken = jwtTokenHandler.ReadToken( reader ) as JwtSecurityToken; jwtTokenHandler.ValidateToken( jwtToken.RawData ); } if ( display ) { Console.WriteLine( string.Format( validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken.RawData )", iterations, DateTime.UtcNow - started ) ); } }
public void CreateAndValidateTokens_JsonClaims() { List<string> errors = new List<string>(); string issuer = "http://www.GotJWT.com"; string claimSources = "_claim_sources"; string claimNames = "_claim_names"; JwtPayload jwtPayloadClaimSources = new JwtPayload(); jwtPayloadClaimSources.Add(claimSources, JsonClaims.ClaimSources); jwtPayloadClaimSources.Add(claimNames, JsonClaims.ClaimNames); JwtSecurityToken jwtClaimSources = new JwtSecurityToken( new JwtHeader(), jwtPayloadClaimSources); JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler(); string encodedJwt = jwtHandler.WriteToken(jwtClaimSources); var validationParameters = new TokenValidationParameters { IssuerValidator = (s, st, tvp) => { return issuer;}, RequireSignedTokens = false, ValidateAudience = false, ValidateLifetime = false, }; SecurityToken validatedJwt = null; var claimsPrincipal = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedJwt); if (!IdentityComparer.AreEqual (claimsPrincipal.Identity as ClaimsIdentity, JsonClaims.ClaimsIdentityDistributedClaims(issuer, TokenValidationParameters.DefaultAuthenticationType, JsonClaims.ClaimSources, JsonClaims.ClaimNames))) { errors.Add("JsonClaims.ClaimSources, JsonClaims.ClaimNames: test failed"); }; Claim c = claimsPrincipal.FindFirst(claimSources); if (!c.Properties.ContainsKey(JwtSecurityTokenHandler.JsonClaimTypeProperty)) { errors.Add(claimSources + " claim, did not have json property: " + JwtSecurityTokenHandler.JsonClaimTypeProperty); } else { if (!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary<string, object>).ToString(), StringComparison.Ordinal)) { errors.Add("!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary<string, object>).ToString(), StringComparison.Ordinal)" + "value is: " + c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty]); } } JwtSecurityToken jwtWithEntity = new JwtSecurityToken( new JwtHeader(), new JwtPayload(claims: ClaimSets.EntityAsJsonClaim(issuer, issuer))); encodedJwt = jwtHandler.WriteToken(jwtWithEntity); JwtSecurityToken jwtRead = jwtHandler.ReadToken(encodedJwt) as JwtSecurityToken; SecurityToken validatedToken; var cp = jwtHandler.ValidateToken(jwtRead.RawData, validationParameters, out validatedToken); Claim jsonClaim = cp.FindFirst(typeof(Entity).ToString()); if (jsonClaim == null) { errors.Add("Did not find Jsonclaims. Looking for claim of type: '" + typeof(Entity).ToString() + "'"); }; string jsString = JsonExtensions.SerializeToJson(Entity.Default); if (!string.Equals(jsString, jsonClaim.Value, StringComparison.Ordinal)) { errors.Add(string.Format(CultureInfo.InvariantCulture, "Find Jsonclaims of type: '{0}', but they weren't equal.\nExpecting:\n'{1}'.\nReceived:\n'{2}'", typeof(Entity).ToString(), jsString, jsonClaim.Value)); } TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors); }
private static bool VerifyToken(string token) { if (string.IsNullOrEmpty(token)) return false; // Read the token var decoder = new JwtSecurityTokenHandler(); JwtSecurityToken decoded = decoder.ReadToken(token) as JwtSecurityToken; return decoded.ValidFrom < DateTime.UtcNow && decoded.ValidTo > DateTime.UtcNow + TimeSpan.FromMinutes(1); }