private void ValidateDerived(string jwt, DerivedJwtSecurityTokenHandler handler, TokenValidationParameters validationParameters, ExpectedException expectedException)
 {
     try
     {
         SecurityToken validatedToken;
         handler.ValidateToken(jwt, validationParameters, out validatedToken);
         Assert.IsNotNull(handler.Jwt as DerivedJwtSecurityToken);
         Assert.IsTrue(handler.ReadTokenCalled);
         Assert.IsFalse(handler.ValidateAudienceCalled);
         Assert.IsTrue(handler.ValidateIssuerCalled);
         Assert.IsTrue(handler.ValidateIssuerSigningKeyCalled);
         Assert.IsTrue(handler.ValidateLifetimeCalled);
         Assert.IsTrue(handler.ValidateSignatureCalled);
         expectedException.ProcessNoException();
     }
     catch (Exception ex)
     {
         expectedException.ProcessException(ex);
     }
 }
示例#2
0
        public void AsymmetricSignatureProvider_Extensibility()
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            Console.WriteLine("Testvariation: " + "outbound signature algorithm - bobsYourUncle");

            // inbound signature algorithm - bobsYourUncle
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.RsaSha256Signature);
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.RsaSha256Signature, "bobsYourUncle"));
            JwtSecurityToken     jwt    = handler.CreateToken(issuer: Issuers.GotJwt, signingCredentials: KeyingMaterial.X509SigningCreds_2048_RsaSha2_Sha2) as JwtSecurityToken;
            List <SecurityToken> tokens = new List <SecurityToken>()
            {
                KeyingMaterial.X509Token_2048
            };

            handler.Configuration = new SecurityTokenHandlerConfiguration()
            {
                IssuerTokenResolver  = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true),
                SaveBootstrapContext = true,
                CertificateValidator = AlwaysSucceedCertificateValidator.New,
                AudienceRestriction  = new AudienceRestriction(AudienceUriMode.Never),
            };

            // inbound unknown algorithm
            ExpectedException expectedException = ExpectedException.SecVal(id: "Jwt10316");

            try
            {
                handler.ValidateToken(jwt);
                ExpectedException.ProcessNoException(expectedException);
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(expectedException, ex);
            }
            finally
            {
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.RsaSha256Signature);
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.RsaSha256Signature, "RS256"));
            }
        }
示例#3
0
        public void SymmetricSignatureProvider_Extensibility()
        {
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            Console.WriteLine("Testvariation: " + "outbound signature algorithm - bobsYourUncle");

            // inbound signature algorithm - bobsYourUncle
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.HmacSha256Signature);
            JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.HmacSha256Signature, "bobsYourUncle"));
            JwtSecurityToken     jwt    = handler.CreateToken(issuer: "http://GotJwt.com", signingCredentials: KeyingMaterial.SymmetricSigningCreds_256_Sha2) as JwtSecurityToken;
            List <SecurityToken> tokens = new List <SecurityToken>()
            {
                KeyingMaterial.BinarySecretToken_256
            };
            TokenValidationParameters tvp = new TokenValidationParameters()
            {
                SigningToken    = KeyingMaterial.BinarySecretToken_256,
                AudienceUriMode = AudienceUriMode.Never,
                ValidIssuer     = "http://GotJwt.com",
            };

            // inbound unknown algorithm
            ExpectedException expectedException = ExpectedException.SecVal(id: "Jwt10316");

            try
            {
                ClaimsPrincipal principal = handler.ValidateToken(jwt, tvp);
                ExpectedException.ProcessNoException(expectedException);
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(expectedException, ex);
            }
            finally
            {
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Remove(SecurityAlgorithms.HmacSha256Signature);
                JwtSecurityTokenHandler.OutboundAlgorithmMap.Add(new KeyValuePair <string, string>(SecurityAlgorithms.HmacSha256Signature, "HS256"));
            }
        }
示例#4
0
        private void FactoryCreateFor(string testcase, SecurityKey key, string algorithm, SignatureProviderFactory factory, ExpectedException expectedException)
        {
            Console.WriteLine(string.Format("Testcase: '{0}'", testcase));

            try
            {
                if (testcase.StartsWith("Siging"))
                {
                    factory.CreateForSigning(key, algorithm);
                }
                else
                {
                    factory.CreateForVerifying(key, algorithm);
                }

                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
        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()));
                }
            }
        }
示例#6
0
        private void AsymmetricConstructorVariation(string testcase, AsymmetricSecurityKey key, string algorithm, ExpectedException expectedException)
        {
            Console.WriteLine(string.Format("Testcase: '{0}'", testcase));

            AsymmetricSignatureProvider provider = null;

            try
            {
                if (testcase.StartsWith("Signing"))
                {
                    provider = new AsymmetricSignatureProvider(key, algorithm, true);
                }
                else
                {
                    provider = new AsymmetricSignatureProvider(key, algorithm, false);
                }
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
        public void JwtSecurityTokenRequirement_Constructor()
        {
            // This class is a bit thin, most of the tests are in JwtConfigTests, just added a couple of missed cases that are easy to code directly.

            // *** null param
            JwtSecurityTokenRequirement JwtSecurityTokenRequirement;
            ExpectedException           expectedException = new ExpectedException(typeExpected: typeof(ArgumentNullException), substringExpected: "element");

            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(null);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            // *** wrong namespace
            XmlDocument xmlDocument = new XmlDocument();

            expectedException = ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10601");
            XmlElement xmlElement = new CustomXmlElement("prefix", "localName", "http://www.gotJwt.com", xmlDocument);

            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(xmlElement);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            // *** unknown X509RevocationMode
            expectedException = ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10606");
            xmlElement        = new CustomXmlElement("prefix", "jwtSecurityTokenRequirement", "http://www.gotJwt.com", xmlDocument);
            xmlElement.Attributes.Append(new CustomXmlAttribute("prefix", "issuerCertificateRevocationMode", "http://www.gotJwt.com", xmlDocument)
            {
                Value = "UnKnown:issuerCertificateRevocationMode",
            });
            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(xmlElement);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            // *** unknown ValidationMode
            expectedException = ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10606");
            xmlElement        = new CustomXmlElement("prefix", "jwtSecurityTokenRequirement", "http://www.gotJwt.com", xmlDocument);
            xmlElement.Attributes.Append(new CustomXmlAttribute("prefix", "issuerCertificateValidationMode", "http://www.gotJwt.com", xmlDocument)
            {
                Value = "UnKnown:issuerCertificateValidationMode",
            });
            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(xmlElement);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            // *** unknown TrustedStoreLocation
            expectedException = ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10606");
            xmlElement        = new CustomXmlElement("prefix", "jwtSecurityTokenRequirement", "http://www.gotJwt.com", xmlDocument);
            xmlElement.Attributes.Append(new CustomXmlAttribute("prefix", "issuerCertificateTrustedStoreLocation", "http://www.gotJwt.com", xmlDocument)
            {
                Value = "UnKnown:issuerCertificateTrustedStoreLocation",
            });
            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(xmlElement);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }

            // *** unbale to create type
            expectedException = ExpectedException.ConfigurationErrorsException(substringExpected: "Jwt10613", inner: typeof(TypeLoadException));
            xmlElement        = new CustomXmlElement("prefix", "jwtSecurityTokenRequirement", "http://www.gotJwt.com", xmlDocument);
            xmlElement.Attributes.Append(new CustomXmlAttribute("prefix", "issuerCertificateValidator", "http://www.gotJwt.com", xmlDocument)
            {
                Value = "UnKnown:issuerCertificateValidatorType",
            });

            xmlElement.Attributes.Append(new CustomXmlAttribute("prefix", "issuerCertificateValidationMode", "http://www.gotJwt.com", xmlDocument)
            {
                Value = "Custom",
            });

            try
            {
                JwtSecurityTokenRequirement = new JwtSecurityTokenRequirement(xmlElement);
                expectedException.ProcessNoException();
            }
            catch (Exception exception)
            {
                expectedException.ProcessException(exception);
            }
        }
示例#8
0
        public void SignatureProviderFactory_Tests()
        {
            SignatureProviderFactory factory = new SignatureProviderFactory();

            // Asymmetric / Symmetric both need signature alg specified
            FactoryCreateFor("Siging:    - algorithm string.Empty", KeyingMaterial.AsymmetricKey_1024, string.Empty, factory, ExpectedException.ArgumentException());
            FactoryCreateFor("Verifying: - algorithm string.Empty", KeyingMaterial.AsymmetricKey_1024, string.Empty, factory, ExpectedException.ArgumentException());

            // Keytype not supported
            FactoryCreateFor("Siging:    - SecurityKey type not Asymmetric or Symmetric", NotAsymmetricOrSymmetricSecurityKey.New, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.ArgumentException("IDX10600:"));
            FactoryCreateFor("Verifying: - SecurityKey type not Asymmetric or Symmetric", NotAsymmetricOrSymmetricSecurityKey.New, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.ArgumentException("IDX10600:"));

            // Private keys missing
            FactoryCreateFor("Siging:    - SecurityKey without private key", KeyingMaterial.DefaultAsymmetricKey_Public_2048, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.InvalidOperationException(substringExpected: "IDX10614:", inner: typeof(NotSupportedException)));
            FactoryCreateFor("Verifying: - SecurityKey without private key", KeyingMaterial.DefaultAsymmetricKey_Public_2048, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.NoExceptionExpected);

            // Key size checks
            FactoryCreateFor("Siging:    - AsymmetricKeySize Key to small", KeyingMaterial.AsymmetricKey_1024, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10630:"));

            SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying = 2048;
            FactoryCreateFor("Verifying: - AsymmetricKeySize Key to small", KeyingMaterial.AsymmetricKey_1024, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10631:"));
            SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying = SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForVerifying;

            SignatureProviderFactory.MinimumSymmetricKeySizeInBits = 512;
            FactoryCreateFor("Siging:    - SymmetricKeySize Key to small", KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10603:"));
            FactoryCreateFor("Verifying: - SymmetricKeySize Key to small", KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10603"));
            SignatureProviderFactory.MinimumSymmetricKeySizeInBits = SignatureProviderFactory.AbsoluteMinimumSymmetricKeySizeInBits;

            ExpectedException expectedException = ExpectedException.ArgumentOutOfRangeException("IDX10613:");

            // setting keys too small
            try
            {
                Console.WriteLine(string.Format("Testcase: '{0}'", "SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning < AbsoluteMinimumAsymmetricKeySizeInBitsForSigning"));
                SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning = SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForSigning - 10;
                expectedException.ProcessNoException();
                SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForSigning = SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForSigning;
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }

            expectedException = ExpectedException.ArgumentOutOfRangeException("IDX10627:");
            try
            {
                Console.WriteLine(string.Format("Testcase: '{0}'", "SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying < AbsoluteMinimumAsymmetricKeySizeInBitsForVerifying"));
                SignatureProviderFactory.MinimumAsymmetricKeySizeInBitsForVerifying = SignatureProviderFactory.AbsoluteMinimumAsymmetricKeySizeInBitsForVerifying - 10;
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }

            expectedException = ExpectedException.ArgumentOutOfRangeException("IDX10628:");
            try
            {
                Console.WriteLine(string.Format("Testcase: '{0}'", "SignatureProviderFactory.MinimumSymmetricKeySizeInBits < AbsoluteMinimumSymmetricKeySizeInBits"));
                SignatureProviderFactory.MinimumSymmetricKeySizeInBits = SignatureProviderFactory.AbsoluteMinimumSymmetricKeySizeInBits - 10;
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }