public void CreateAndValidateTokens_RoleClaims() { JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); TokenValidationParameters validationParameters = new TokenValidationParameters { IssuerSigningToken = KeyingMaterial.DefaultX509Token_2048, ValidateAudience = false, ValidateIssuer = false, }; string issuer = "https://gotjwt.com"; DateTime utcNow = DateTime.UtcNow; DateTime expire = utcNow + TimeSpan.FromHours(1); ClaimsIdentity subject = new ClaimsIdentity(claims: ClaimSets.RoleClaimsShortType(issuer, issuer)); JwtSecurityToken jwtToken = handler.CreateToken(issuer: issuer, signingCredentials: KeyingMaterial.DefaultX509SigningCreds_2048_RsaSha2_Sha2, subject: subject) as JwtSecurityToken; SecurityToken securityToken; ClaimsPrincipal principal = handler.ValidateToken(jwtToken.RawData, validationParameters, out securityToken); CheckForRoles(new string[] { "role1", "roles1" }, new string[] { "notrole1", "notrole2" }, principal); ClaimsIdentity expectedIdentity = new ClaimsIdentity( authenticationType: "Federation", claims: ClaimSets.RoleClaimsLongType(issuer, issuer) ); Claim claim = new Claim(type: JwtRegisteredClaimNames.Iss, value: issuer, valueType: ClaimValueTypes.String, issuer: issuer); expectedIdentity.AddClaim(claim); claim = new Claim(JwtRegisteredClaimNames.Exp, EpochTime.GetIntDate(expire).ToString(), valueType: "JSON", issuer: issuer); claim.Properties.Add(JwtSecurityTokenHandler.JsonClaimTypeProperty, "System.Int32"); expectedIdentity.AddClaim(claim); claim = new Claim(JwtRegisteredClaimNames.Nbf, EpochTime.GetIntDate(utcNow).ToString(), valueType: "JSON", issuer: issuer); claim.Properties.Add(JwtSecurityTokenHandler.JsonClaimTypeProperty, "System.Int32"); expectedIdentity.AddClaim(claim); CompareContext context = new CompareContext(); IdentityComparer.AreEqual <IEnumerable <Claim> >(principal.Claims, expectedIdentity.Claims, context); Assert.IsTrue(context.Errors.Count == 0); }
private void RunRoundTrip(CreateAndValidateParams jwtParams, JwtSecurityTokenHandler handler) { SecurityToken validatedToken; 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 RoundTripTokens() { 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); handler.ValidateToken(jwt, jwtParams.TokenValidationParameters); // 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; tokenDescriptor.AppliesToAddress = jwtParams.CompareTo.Audience; JwtSecurityToken token = handler.CreateToken(tokenDescriptor) as JwtSecurityToken; Assert.IsFalse(!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(); handler.CertificateValidator = X509CertificateValidator.None; token = handler.ReadToken(reader) as JwtSecurityToken; ms.Close(); IdentityComparer.AreEqual(token, jwtParams.CompareTo); } }
private void RunConstructionTest(JwtSecurityTokenTestVariation variation) { JwtSecurityToken jwt = null; try { jwt = new JwtSecurityToken( issuer: variation.Issuer, audience: variation.Audience, claims: variation.Claims, signingCredentials: variation.SigningCredentials, notBefore: variation.NotBefore, expires: variation.Expires); variation.ExpectedException.ProcessNoException(); } catch (Exception ex) { variation.ExpectedException.ProcessException(ex); } try { // ensure we can get to every property if (jwt != null && (variation.ExpectedException == null || variation.ExpectedException.TypeExpected == null)) { TestUtilities.CallAllPublicInstanceAndStaticPropertyGets(jwt, variation.Name); } if (null != variation.ExpectedJwtSecurityToken) { Assert.IsTrue(IdentityComparer.AreEqual(variation.ExpectedJwtSecurityToken, jwt)); } } catch (Exception ex) { Assert.Fail(string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", variation.Name, ex.ToString())); } }
public void JwtSecurityToken_ConstructionParams() { Console.WriteLine(string.Format("Entering: '{0}'", MethodBase.GetCurrentMethod())); JwtSecurityToken jwt = null; foreach (JwtSecurityTokenTestVariation param in JwtConstructionParamsVariations()) { Console.WriteLine(string.Format("Testcase: {0}", param.Name)); try { //jwt = new JWTSecurityToken( issuer: param.Issuer, audience: param.Audience, claims: param.Claims, signingCredentials: param.SigningCredentials, lifetime: param.Lifetime, actor: param.Actor); jwt = new JwtSecurityToken(param.Issuer, param.Audience, param.Claims, new Lifetime(param.ValidFrom, param.ValidTo)); ExpectedException.ProcessNoException(param.ExpectedException); } catch (Exception ex) { ExpectedException.ProcessException(param.ExpectedException, ex); } try { // ensure we can get to every property if (jwt != null && (param.ExpectedException == null || param.ExpectedException.Thrown == null)) { JwtTestUtilities.CallAllPublicInstanceAndStaticPropertyGets(jwt, param.Name); } if (null != param.ExpectedJwtSecurityToken) { Assert.IsFalse(!IdentityComparer.AreEqual(param.ExpectedJwtSecurityToken, jwt), string.Format("Testcase: {0}. JWTSecurityTokens are not equal.", param.Name)); } } catch (Exception ex) { Assert.Fail(string.Format("Testcase: {0}. UnExpected when getting a properties: '{1}'", param.Name, ex.ToString())); } } }
public static bool AreEqual(JwtPayload payload1, JwtPayload payload2) { if (payload1 == null && payload2 == null) { return(true); } if (null == payload1 || null == payload2) { return(false); } if (payload1.Count != payload2.Count) { return(false); } if (!IdentityComparer.AreEqual(payload1.Claims, payload2.Claims)) { return(false); } return(true); }
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); }
public void TokenValidationParameters_Publics() { TokenValidationParameters validationParameters = new TokenValidationParameters(); Type type = typeof(TokenValidationParameters); PropertyInfo[] properties = type.GetProperties(); if (properties.Length != 30) { Assert.Fail("Number of properties has changed from 30 to: " + properties.Length + ", adjust tests"); } SecurityKey issuerSigningKey = KeyingMaterial.DefaultSymmetricSecurityKey_256; SecurityKey issuerSigningKey2 = KeyingMaterial.SymmetricSecurityKey2_256; List <SecurityKey> issuerSigningKeys = new List <SecurityKey> { KeyingMaterial.DefaultSymmetricSecurityKey_256, KeyingMaterial.SymmetricSecurityKey2_256 }; List <SecurityKey> issuerSigningKeysDup = new List <SecurityKey> { new InMemorySymmetricSecurityKey(KeyingMaterial.SymmetricKeyBytes2_256), new InMemorySymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_256) }; string validAudience = "ValidAudience"; List <string> validAudiences = new List <string> { validAudience }; string validIssuer = "ValidIssuer"; List <string> validIssuers = new List <string> { validIssuer }; TokenValidationParameters validationParametersInline = new TokenValidationParameters() { AudienceValidator = IdentityUtilities.AudienceValidatorReturnsTrue, IssuerSigningKey = issuerSigningKey, IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tvp) => { return(issuerSigningKey); }, IssuerSigningKeys = issuerSigningKeys, IssuerValidator = IdentityUtilities.IssuerValidatorEcho, LifetimeValidator = IdentityUtilities.LifetimeValidatorReturnsTrue, SaveSigninToken = true, ValidateAudience = false, ValidateIssuer = false, ValidAudience = validAudience, ValidAudiences = validAudiences, ValidIssuer = validIssuer, ValidIssuers = validIssuers, }; Assert.IsTrue(object.ReferenceEquals(validationParametersInline.IssuerSigningKey, issuerSigningKey)); Assert.IsTrue(validationParametersInline.SaveSigninToken); Assert.IsFalse(validationParametersInline.ValidateAudience); Assert.IsFalse(validationParametersInline.ValidateIssuer); Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidAudience, validAudience)); Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidAudiences, validAudiences)); Assert.IsTrue(object.ReferenceEquals(validationParametersInline.ValidIssuer, validIssuer)); TokenValidationParameters validationParametersSets = new TokenValidationParameters(); validationParametersSets.AudienceValidator = IdentityUtilities.AudienceValidatorReturnsTrue; validationParametersSets.IssuerSigningKey = new InMemorySymmetricSecurityKey(KeyingMaterial.DefaultSymmetricKeyBytes_256); validationParametersSets.IssuerSigningKeyResolver = (token, securityToken, keyIdentifier, tvp) => { return(issuerSigningKey2); }; validationParametersSets.IssuerSigningKeys = issuerSigningKeysDup; validationParametersSets.IssuerValidator = IdentityUtilities.IssuerValidatorEcho; validationParametersSets.LifetimeValidator = IdentityUtilities.LifetimeValidatorReturnsTrue; validationParametersSets.SaveSigninToken = true; validationParametersSets.ValidateAudience = false; validationParametersSets.ValidateIssuer = false; validationParametersSets.ValidAudience = validAudience; validationParametersSets.ValidAudiences = validAudiences; validationParametersSets.ValidIssuer = validIssuer; validationParametersSets.ValidIssuers = validIssuers; Assert.IsTrue(IdentityComparer.AreEqual <TokenValidationParameters>(validationParametersInline, validationParametersSets)); TokenValidationParameters tokenValidationParametersCloned = validationParametersInline.Clone() as TokenValidationParameters; Assert.IsTrue(IdentityComparer.AreEqual <TokenValidationParameters>(tokenValidationParametersCloned, validationParametersInline)); //tokenValidationParametersCloned.AudienceValidator(new string[]{"bob"}, JwtTestTokens.Simple(); string id = Guid.NewGuid().ToString(); DerivedTokenValidationParameters derivedValidationParameters = new DerivedTokenValidationParameters(id, validationParametersInline); DerivedTokenValidationParameters derivedValidationParametersCloned = derivedValidationParameters.Clone() as DerivedTokenValidationParameters; Assert.IsTrue(IdentityComparer.AreEqual <TokenValidationParameters>(derivedValidationParameters, derivedValidationParametersCloned)); Assert.AreEqual(derivedValidationParameters.InternalString, derivedValidationParametersCloned.InternalString); }
public static bool AreEqual(JwtSecurityToken jwt1, JwtSecurityToken jwt2, bool expectRawData = false) { if (jwt1 == null && jwt2 == null) { return(true); } if (null == jwt1 || null == jwt2) { return(false); } if (!AreEqual(jwt1.Header, jwt2.Header)) { return(false); } if (!AreEqual(jwt1.Payload, jwt2.Payload)) { return(false); } if (!IdentityComparer.AreEqual(jwt1.Claims, jwt2.Claims)) { return(false); } if (jwt1.Actor != jwt2.Actor) { return(false); } if (!AreEqual(jwt1.Audience, jwt2.Audience)) { return(false); } if (!AreEqual(jwt1.Id, jwt2.Id)) { return(false); } if (!AreEqual(jwt1.Issuer, jwt2.Issuer)) { return(false); } if (expectRawData && !AreEqual(jwt1.RawData, jwt2.RawData)) { return(false); } if (!AreEqual(jwt1.SignatureAlgorithm, jwt2.SignatureAlgorithm)) { return(false); } if (jwt1.ValidFrom != jwt2.ValidFrom) { return(false); } if (jwt1.ValidTo != jwt2.ValidTo) { return(false); } // no reason to check keys, as they are always empty. //ReadOnlyCollection<SecurityKey> keys = jwt.SecurityKeys; return(true); }
public static bool AreEqual(ClaimsIdentity ci1, ClaimsIdentity ci2, bool ignoreType = false) { if (ci1 == null && ci2 == null) { return(true); } if (ci1 == null || ci2 == null) { return(false); } if (!ignoreType) { if (ci1.GetType() != ci2.GetType()) { return(false); } } if (!IdentityComparer.AreEqual(ci1.Actor, ci2.Actor)) { return(false); } if (StringComparer.OrdinalIgnoreCase.Compare(ci1.AuthenticationType, ci2.AuthenticationType) != 0) { return(false); } //if (!IdentityComparer45.AreEqual(ci1.BootstrapContext as ISerializable, ci2.BootstrapContext as ISerializable)) // return false; if (!IdentityComparer.AreEqual(ci1.Claims, ci2.Claims)) { return(false); } if (ci1.IsAuthenticated != ci2.IsAuthenticated) { return(false); } if (StringComparer.Ordinal.Compare(ci1.Label, ci2.Label) != 0) { return(false); } if (StringComparer.Ordinal.Compare(ci1.Name, ci2.Name) != 0) { return(false); } if (StringComparer.OrdinalIgnoreCase.Compare(ci1.NameClaimType, ci2.NameClaimType) != 0) { return(false); } if (StringComparer.OrdinalIgnoreCase.Compare(ci1.RoleClaimType, ci2.RoleClaimType) != 0) { return(false); } return(true); }
public static bool AreEqual(IEnumerable <Claim> claims1, IEnumerable <Claim> claims2) { if (claims1 == null && claims2 == null) { return(true); } if (claims1 == null || claims2 == null) { return(false); } List <Claim> claims1Claims = new List <Claim>(); List <Claim> claims1ClaimsMatched = new List <Claim>(); List <Claim> claims2Claims = new List <Claim>(); List <bool> claims2Matched = new List <bool>(); foreach (Claim c in claims1) { claims1Claims.Add(c); } foreach (Claim c in claims2) { claims2Matched.Add(false); claims2Claims.Add(c); } if (claims1Claims.Count != claims2Claims.Count) { return(false); } int numDups = 0; Claim c1 = null; Claim c2 = null; for (int i = 0; i < claims1Claims.Count; i++) { bool matched = false; c1 = claims1Claims[i]; for (int j = 0; j < claims2Claims.Count; j++) { c2 = claims2Claims[j]; if (IdentityComparer.AreEqual(c1, c2)) { // claim can only match once. if (!claims2Matched[j]) { matched = true; claims2Matched[j] = true; claims1ClaimsMatched.Add(c1); break; } else { numDups++; } } } if (!matched) { return(false); } } foreach (bool found in claims2Matched) { if (!found) { return(false); } } return(true); }