public void CreateTokenAndParseEncodedMultipleClaims()
        {
            var handler = new SimpleWebTokenHandler();

            byte[] key = GetKey();
            var token = this.CreateToken(key);
            var tokenString = TokenToString(token);
            var signedToken = handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            handler.Configuration = new SecurityTokenHandlerConfiguration();

            var symmetricKey = new InMemorySymmetricSecurityKey(key);
            
            handler.Configuration.AudienceRestriction.AllowedAudienceUris.Add(
                new Uri("http://audience"));

            var resolverTable = new Dictionary<string, IList<SecurityKey>>
            {
                { "http://issuer", new SecurityKey[] { symmetricKey } }
            };

            handler.Configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var ids = handler.ValidateToken(signedToken);
            var id = ids.FirstOrDefault();
            
            Assert.IsNotNull(id);

            var testClaims = GetClaims();

            Assert.IsTrue(id.Claims.Count() == 3);
            Assert.IsTrue(id.HasClaim(testClaims[0].Type, testClaims[0].Value));
            Assert.IsTrue(id.HasClaim(testClaims[1].Type, testClaims[1].Value));
            Assert.IsTrue(id.HasClaim(testClaims[2].Type, testClaims[2].Value));
        }
Ejemplo n.º 2
0
		public DerivedKeySecurityToken (string id, string algorithm,
			SecurityKeyIdentifierClause reference,
			SymmetricSecurityKey referencedKey,
			string name,
			int? generation,
			int? offset,
			int? length,
			string label,
			byte [] nonce)
		{
			algorithm = algorithm ?? SecurityAlgorithms.Psha1KeyDerivation;

			this.id = id;
			this.algorithm = algorithm;
			this.reference = reference;
			this.generation = generation;
			this.offset = offset;
			this.length = length;
			this.nonce = nonce;
			this.name = name;
			this.label = label;

			SecurityKey key = new InMemorySymmetricSecurityKey (
				referencedKey.GenerateDerivedKey (
					algorithm,
					Encoding.UTF8.GetBytes (label ?? Constants.WsscDefaultLabel),
					nonce,
					(length ?? 32) * 8,
					offset ?? 0));
			keys = new ReadOnlyCollection<SecurityKey> (
				new SecurityKey [] {key});
		}
        private static void ValidateSwtToken(string tokenString)
        {
            var configuration = new SecurityTokenHandlerConfiguration();
            var validationKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingKey));

            // audience validation
            configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(realm));

            // signature & issuer validation
            var resolverTable = new Dictionary<string, IList<SecurityKey>>
            {
                { issuerUri, new SecurityKey[] { validationKey } }
            };

            configuration.IssuerTokenResolver = new NamedKeyIssuerTokenResolver(resolverTable);

            var handler = new SimpleWebTokenHandler();
            handler.Configuration = configuration;

            var token = handler.ReadToken(tokenString);
            var ids = handler.ValidateToken(token);

            "\n\nValidated Claims:".ConsoleYellow();
            foreach (var claim in ids.First().Claims)
            {
                Console.WriteLine("{0}\n {1}\n", claim.Type, claim.Value);
            }
        }
        public override SecurityKey CreateKey()
        {
            if (this.symmetricKey == null)
                this.symmetricKey = new InMemorySymmetricSecurityKey(GetBuffer(), false);

            return this.symmetricKey;
        }
        public void GetSymmetricAlgorithmAES()
        {
            byte []            bytes = new byte [32];
            Key                key   = new Key(bytes);
            SymmetricAlgorithm alg   = key.GetSymmetricAlgorithm(
                SecurityAlgorithms.Aes128Encryption);

            Assert.AreEqual(256, alg.KeySize, "#1-1");
            Assert.AreEqual(CipherMode.CBC, alg.Mode, "#1-2");
            Assert.AreEqual(PaddingMode.PKCS7, alg.Padding, "#1-3");
            alg = key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes192Encryption);
            Assert.AreEqual(256, alg.KeySize, "#2-1");
            Assert.AreEqual(CipherMode.CBC, alg.Mode, "#2-2");
            Assert.AreEqual(PaddingMode.PKCS7, alg.Padding, "#2-3");
            alg = key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes256Encryption);
            Assert.AreEqual(256, alg.KeySize, "#3-1");
            Assert.AreEqual(CipherMode.CBC, alg.Mode, "#3-2");
            Assert.AreEqual(PaddingMode.PKCS7, alg.Padding, "#3-3");

            alg = key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes128KeyWrap);
            Assert.IsTrue(alg is AES, "#4");
            alg = key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes192KeyWrap);
            Assert.IsTrue(alg is AES, "#5");
            alg = key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes256KeyWrap);
            Assert.IsTrue(alg is AES, "#6");
            //alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.TripleDesKeyWrap);
            //Assert.IsTrue (alg is TripleDES, "#7");
        }
		public void CreateSimple ()
		{
			Key key = new Key (raw);
			Assert.AreEqual (256, key.KeySize, "#1");
			// the returned value must be a clone.
			Assert.IsFalse (Object.ReferenceEquals (key.GetSymmetricKey (), raw), "#2");
		}
Ejemplo n.º 7
0
        static string BearerToken()
        {
            var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";

            var securityKey = Convert.FromBase64String(mainKey);
            var inMemKey = new InMemorySymmetricSecurityKey(securityKey);

            ClaimsIdentity identity = new ClaimsIdentity();
            identity.AddClaim(new Claim("scope", "Full"));

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
            SecurityToken securityToken = handler.CreateToken(new SecurityTokenDescriptor()
            {
                TokenType = "Bearer",
                Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddHours(1)),
                SigningCredentials = new SigningCredentials(inMemKey, signatureAlgorithm, digestAlgorithm),
                //This data I would get by matching the jwtSecurityToken.Audience to database or something
                TokenIssuerName = "PaulsSite",
                AppliesToAddress = "http://JoshsSite",
                Subject = identity
            }
            );

            return handler.WriteToken(securityToken);
        }
		public void GetSymmetricAlgorithmAES ()
		{
			byte [] bytes = new byte [32];
			Key key = new Key (bytes);
			SymmetricAlgorithm alg = key.GetSymmetricAlgorithm (
				SecurityAlgorithms.Aes128Encryption);
			Assert.AreEqual (256, alg.KeySize, "#1-1");
			Assert.AreEqual (CipherMode.CBC, alg.Mode, "#1-2");
			Assert.AreEqual (PaddingMode.PKCS7, alg.Padding, "#1-3");
			alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.Aes192Encryption);
			Assert.AreEqual (256, alg.KeySize, "#2-1");
			Assert.AreEqual (CipherMode.CBC, alg.Mode, "#2-2");
			Assert.AreEqual (PaddingMode.PKCS7, alg.Padding, "#2-3");
			alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.Aes256Encryption);
			Assert.AreEqual (256, alg.KeySize, "#3-1");
			Assert.AreEqual (CipherMode.CBC, alg.Mode, "#3-2");
			Assert.AreEqual (PaddingMode.PKCS7, alg.Padding, "#3-3");

			alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.Aes128KeyWrap);
			Assert.IsTrue (alg is AES, "#4");
			alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.Aes192KeyWrap);
			Assert.IsTrue (alg is AES, "#5");
			alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.Aes256KeyWrap);
			Assert.IsTrue (alg is AES, "#6");
			//alg = key.GetSymmetricAlgorithm (SecurityAlgorithms.TripleDesKeyWrap);
			//Assert.IsTrue (alg is TripleDES, "#7");
		}
 public SimpleWebToken(Uri audienceUri, string issuer, DateTime expiresOn, List<Claim> claims, InMemorySymmetricSecurityKey signingKey)
 {
     _audienceUri = audienceUri;
     _issuer = issuer;
     _expiresOn = expiresOn;
     _claims = claims;
     _signingKey = signingKey;
 }
Ejemplo n.º 10
0
        public SimpleWebToken2(string key)
        {
            TimeSpan ts = DateTime.UtcNow - epochStart + lifeTime;
            this.ExpiresOn = Convert.ToUInt64(ts.TotalSeconds);

            var securityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(key));
            keyBytes = securityKey.GetSymmetricKey();
        }
        public void CreateSimple()
        {
            Key key = new Key(raw);

            Assert.AreEqual(256, key.KeySize, "#1");
            // the returned value must be a clone.
            Assert.IsFalse(Object.ReferenceEquals(key.GetSymmetricKey(), raw), "#2");
        }
        [ExpectedException(typeof(InvalidOperationException))]           // not ArgumentNullException?
        public void GenerateDerivedKeyNullAlgorithm()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            key.GenerateDerivedKey(null, wssc_label, nonce, key.KeySize, 0);
        }
        [ExpectedException(typeof(InvalidOperationException))]           // not ArgumentNullException?
        public void GenerateDerivedKeyUnsupportedAlgorithm()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            key.GenerateDerivedKey("urn:my-own-way", wssc_label, nonce, key.KeySize, 0);
        }
        public void IsSymmetricAlgorithm()
        {
            Key key = new Key(raw);

            Assert.IsTrue(key.IsSymmetricAlgorithm(SecurityAlgorithms.Aes256KeyWrap), "#1");
            Assert.IsTrue(key.IsSymmetricAlgorithm(SecurityAlgorithms.TripleDesEncryption), "#2");
            Assert.IsFalse(key.IsSymmetricAlgorithm(SecurityAlgorithms.RsaOaepKeyWrap), "#3");
            Assert.IsTrue(key.IsSymmetricAlgorithm(SecurityAlgorithms.Psha1KeyDerivation), "#4");
        }
        public void GetSymmetricAlgorithm3VulnerableTDESEnc()
        {
            byte [] bytes = new byte [24];
            Key     key   = new Key(bytes);

            // strange, TripleDesEncryption works with 32bytes key,
            // but TripleDesKeyWrap doesn't.
            key.GetSymmetricAlgorithm(SecurityAlgorithms.TripleDesEncryption);
        }
        public void GenerateDerivedKeyUnusualOffset()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            key.GenerateDerivedKey(
                SecurityAlgorithms.Psha1KeyDerivation,
                wssc_label, nonce, 5, 0);
        }
        public void GenerateDerivedKeyNullNonce()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            key.GenerateDerivedKey(
                SecurityAlgorithms.Psha1KeyDerivation,
                wssc_label, null, key.KeySize, 0);
        }
        public void GenerateDerivedKeyNegativeLength()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            key.GenerateDerivedKey(
                SecurityAlgorithms.Psha1KeyDerivation,
                wssc_label, nonce, -32, 0);
        }
        // no error???
        public void GetSymmetricAlgorithmWrongSize2()
        {
            AES aes = new AES();

            aes.KeySize = 192;
            aes.GenerateKey();
            Key key = new Key(aes.Key);

            Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes256Encryption));
        }
Ejemplo n.º 20
0
 private static SecurityTokenDescriptor CreateSecurityTokenDescriptor(List<Claim> claims, InMemorySymmetricSecurityKey key)
 {
     return new SecurityTokenDescriptor
     {
         TokenIssuerName = TokenConstants.TokenIssuer,
         AppliesToAddress = TokenConstants.TokenAudience,
         Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(TokenConstants.TokenLifetimeInMinutes)),
         Subject = new ClaimsIdentity(claims.ToArray()),
         SigningCredentials = new SigningCredentials(key,
             "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
             "http://www.w3.org/2001/04/xmlenc#sha256"),
     };
 }
        public SimpleWebToken()
        {
            TimeSpan ts = DateTime.UtcNow - EpochStart + LifeTime;
            ExpiresOn = Convert.ToUInt64(ts.TotalSeconds);
            _keyValuePairs = new NameValueCollection();

            var key = RoleEnvironment.GetConfigurationSettingValue("SimpleWebTokenKey");
            var securityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(key));
            _keyBytes = securityKey.GetSymmetricKey();

            Issuer = "ToSavour";
            Audience = "ToSavour";
        }
Ejemplo n.º 22
0
        /// <summary>
        /// <![CDATA[配置JWT认证]]>
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            var issuer     = "http://localhost:51912/";                                                           //发行者
            var audience   = "fNm0EDIXbfuuDowUpAoq5GTEiywV8eg0TpiIVnV8";                                          //观众
            var secret     = TextEncodings.Base64Url.Decode(OAuthCommon.Constants.Consts.JWT.Security.SecretKey); //秘钥
            var signingKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(secret);

            //令牌验证参数
            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim 颁布者
                ValidateIssuer = true,
                ValidIssuer    = issuer,

                // Validate the JWT Audience (aud) claim 观众
                ValidateAudience = true,
                ValidAudience    = audience,

                // Validate the token expiry
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero,
            };


            //Jwt数据格式
            OAuth.JwtDataFormat jwtDataFormat = new OAuth.JwtDataFormat(issuer: issuer, secret: secret);

            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            app.UseOAuthAuthorizationServer(new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType        = "Bearer",
                AuthorizeEndpointPath     = new PathString("/oauth2/authorize"), //http://localhost:50573/oauth2/authorize?response_type=token&client_id=_auth2.0Client&redirect_uri=http://localhost:50573/api/values/ 主要是授权码和客户端模式
                TokenEndpointPath         = new PathString("/oauth2/token"),     //
                AccessTokenExpireTimeSpan = new TimeSpan(3, 0, 0),
                AccessTokenFormat         = jwtDataFormat,                       //自定义
                RefreshTokenFormat        = jwtDataFormat,
                //AccessTokenProvider = new AuthenticationTokenProvider()
                //{
                //},
                Provider = new OAuth.JwtAuthorizationServerProvider(tokenValidationParameters),
                ApplicationCanDisplayErrors = true,
            });
        }
Ejemplo n.º 23
0
        ReadOnlyCollection <SecurityKey> BuildCryptoList()
        {
            List <SecurityKey> cryptoList = new List <SecurityKey>();

            for (int i = 0; i < this.statements.Count; ++i)
            {
                SamlSubjectStatement statement = this.statements[i] as SamlSubjectStatement;
                if (statement != null)
                {
                    bool        skipCrypto = false;
                    SecurityKey crypto     = null;
                    if (statement.SamlSubject != null)
                    {
                        crypto = statement.SamlSubject.Crypto;
                    }
                    InMemorySymmetricSecurityKey inMemorySymmetricSecurityKey = crypto as InMemorySymmetricSecurityKey;
                    if (inMemorySymmetricSecurityKey != null)
                    {
                        // Verify that you have not already added this to crypto list.
                        for (int j = 0; j < cryptoList.Count; ++j)
                        {
                            if ((cryptoList[j] is InMemorySymmetricSecurityKey) && (cryptoList[j].KeySize == inMemorySymmetricSecurityKey.KeySize))
                            {
                                byte[] key1 = ((InMemorySymmetricSecurityKey)cryptoList[j]).GetSymmetricKey();
                                byte[] key2 = inMemorySymmetricSecurityKey.GetSymmetricKey();
                                int    k    = 0;
                                for (k = 0; k < key1.Length; ++k)
                                {
                                    if (key1[k] != key2[k])
                                    {
                                        break;
                                    }
                                }
                                skipCrypto = (k == key1.Length);
                            }

                            if (skipCrypto)
                            {
                                break;
                            }
                        }
                    }
                    if (!skipCrypto && (crypto != null))
                    {
                        cryptoList.Add(crypto);
                    }
                }
            }

            return(cryptoList.AsReadOnly());
        }
        public void GenerateDerivedKey()
        {
            Key key = new Key(raw);

            byte [] nonce = new byte [256];

            byte [] derived = key.GenerateDerivedKey(
                SecurityAlgorithms.Psha1KeyDerivation,
                wssc_label, nonce, key.KeySize, 0);
            Assert.IsTrue(Convert.ToBase64String(derived) != Convert.ToBase64String(raw), "#4");
            // the precomputed derivation value.
            byte [] expected = Convert.FromBase64String("50UfLeg58TbfADujVeafUAS8typGX9LvqLOXezK/eJY=");
            Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(derived), "#5");
        }
        private ReadOnlyCollection <SecurityKey> BuildCryptoList()
        {
            List <SecurityKey> list = new List <SecurityKey>();

            for (int i = 0; i < this.statements.Count; i++)
            {
                SamlSubjectStatement statement = this.statements[i] as SamlSubjectStatement;
                if (statement != null)
                {
                    bool        flag = false;
                    SecurityKey item = null;
                    if (statement.SamlSubject != null)
                    {
                        item = statement.SamlSubject.Crypto;
                    }
                    InMemorySymmetricSecurityKey key2 = item as InMemorySymmetricSecurityKey;
                    if (key2 != null)
                    {
                        for (int j = 0; j < list.Count; j++)
                        {
                            if ((list[j] is InMemorySymmetricSecurityKey) && (list[j].KeySize == key2.KeySize))
                            {
                                byte[] symmetricKey = ((InMemorySymmetricSecurityKey)list[j]).GetSymmetricKey();
                                byte[] buffer2      = key2.GetSymmetricKey();
                                int    index        = 0;
                                index = 0;
                                while (index < symmetricKey.Length)
                                {
                                    if (symmetricKey[index] != buffer2[index])
                                    {
                                        break;
                                    }
                                    index++;
                                }
                                flag = index == symmetricKey.Length;
                            }
                            if (flag)
                            {
                                break;
                            }
                        }
                    }
                    if (!flag && (item != null))
                    {
                        list.Add(item);
                    }
                }
            }
            return(list.AsReadOnly());
        }
Ejemplo n.º 26
0
        public static string CreateJwtToken(string userName, string role)
        {
            var claimList = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name, userName),
                    new Claim(ClaimTypes.Role, role)     //Not sure what this is for
                };

            var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
            var sSKey = new InMemorySymmetricSecurityKey(SecurityConstants.KeyForHmacSha256);

            var jwtToken = tokenHandler.CreateToken(makeSecurityTokenDescriptor(sSKey, claimList));
            return tokenHandler.WriteToken(jwtToken);
        }
Ejemplo n.º 27
0
 private static SecurityTokenDescriptor makeSecurityTokenDescriptor(InMemorySymmetricSecurityKey sSKey, List<Claim> claimList)
 {
     var now = DateTime.UtcNow;
     Claim[] claims = claimList.ToArray();
     return new SecurityTokenDescriptor
     {
         Subject = new ClaimsIdentity(claims),
         TokenIssuerName = SecurityConstants.TokenIssuer,
         AppliesToAddress = SecurityConstants.TokenAudience,
         Lifetime = new Lifetime(now, now.AddMinutes(SecurityConstants.TokenLifetimeMinutes)),
         SigningCredentials = new SigningCredentials(sSKey,
             "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
             "http://www.w3.org/2001/04/xmlenc#sha256"),
     };
 }
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = null;
            var swtClause = keyIdentifierClause as WebTokenSecurityKeyClause;

            string value;
            if (_signingKeys.TryGetValue(swtClause.Issuer.ToLowerInvariant(), out value))
            {
                key = new InMemorySymmetricSecurityKey(Convert.FromBase64String(value));

                return true;
            }

            return false;
        }
Ejemplo n.º 29
0
 public static Token CreateToken(UserInfo user, string perms)
 {
     var claims = new List<Claim>()
         {
             new Claim(ClaimTypes.UserData, user.UserId.ToString()),
             new Claim(ClaimTypes.PrimarySid, user.UserId.ToString()),
             new Claim(ClaimTypes.Sid, user.UserId.ToString()),
             new Claim(ClaimTypes.Name, user.FullName.ToString())
         };
     var key = new InMemorySymmetricSecurityKey(TokenConstants.TokenKey);
     var jwt = new JwtSecurityTokenHandler() { TokenLifetimeInMinutes = TokenConstants.TokenLifetimeInMinutes };
     var token = jwt.CreateToken(CreateSecurityTokenDescriptor(claims, key));
    
     return new Token() { Value = jwt.WriteToken(token), Expiry = TokenConstants.TokenLifetimeInMinutes, User = user.FullName, Perms = perms };
 }
        public static  SimpleWebToken ToSwtToken(this ClaimsPrincipal principal)
        {
            var identity = principal.Identities.First();
            var context = identity.BootstrapContext as BootstrapContext;
            var claims = identity.Claims.ToList();

            var signValue = ConfigurationManager.AppSettings[SwtConstants.SigningKeyAppSetting];
            var issureValue = ConfigurationManager.AppSettings[SwtConstants.IssureAppSetting];
            var audiencevalue = ConfigurationManager.AppSettings[SwtConstants.AudienceAppSetting];

            var key = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signValue));

            return  new SimpleWebToken(new Uri(audiencevalue),
                issureValue, context.SecurityToken.ValidTo, claims,
                key);;
        }
Ejemplo n.º 31
0
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            key = null;
            CustomTokenKeyIdentifierClause keyClause = keyIdentifierClause as CustomTokenKeyIdentifierClause;
            if (keyClause != null)
            {
                string base64Key = null;
                _keys.TryGetValue(keyClause.Audience, out base64Key);
                if (!string.IsNullOrEmpty(base64Key))
                {
                    key = new InMemorySymmetricSecurityKey(Encoding.UTF8.GetBytes(base64Key));
                    return true;
                }
            }

            return false;
        }
        public virtual async Task<TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true)
        {
            if (clientId.IsMissing())
            {
                clientId = GetClientIdFromJwt(token);

                if (clientId.IsMissing())
                {
                    return Invalid(Constants.ProtectedResourceErrors.InvalidToken);
                }
            }

            var client = await _clients.FindClientByIdAsync(clientId);
            if (client == null)
            {
                return Invalid(Constants.ProtectedResourceErrors.InvalidToken);
            }

            SecurityKey signingKey;
            if (client.IdentityTokenSigningKeyType == SigningKeyTypes.ClientSecret)
            {
                signingKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(client.ClientSecret));
            }
            else
            {
                signingKey = new X509SecurityKey(_options.SigningCertificate);
            }

            var result = await ValidateJwtAsync(token, clientId, signingKey, validateLifetime);
            result.Client = client;

            if (result.IsError)
            {
                return result;
            }

            Logger.Debug("Calling custom token validator");
            var customResult = await _customValidator.ValidateIdentityTokenAsync(result);

            if (customResult.IsError)
            {
                Logger.Error("Custom validator failed: " + customResult.Error ?? "unknown");
            }

            return customResult;
        }
Ejemplo n.º 33
0
        public JwtTokenGenerator()
        {
            var random = new byte[64];
            using (var rng = RandomNumberGenerator.Create())
                rng.GetBytes(random);

            //Use a in memory random generated symetrickey so when the service is restarted, all token generated before restart are invalidated
            var symetricSecurityKey = new InMemorySymmetricSecurityKey(Encoding.ASCII.GetBytes("90htwn5AtMMiKBfRsf8BPlnK0uAmyQejcoV0rVWTatLpEZfZhVIjr3l78N28dAB4"));
            this.credentials = new SigningCredentials(symetricSecurityKey, JwtTokenGenerator.SignatureAlgorithm, JwtTokenGenerator.DigestAlgorithm);

            this.validationParameters = new TokenValidationParameters
            {
                IssuerSigningKey = symetricSecurityKey,
                ValidateAudience = false,
                ValidIssuer = JwtTokenGenerator.TokenIssuer
            };
        }
        /// <summary>
        /// Resolves the given SecurityKeyIdentifierClause to a SecurityKey.
        /// </summary>
        /// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve</param>
        /// <param name="key">The resolved SecurityKey.</param>
        /// <returns>True if successfully resolved.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            if (keyIdentifierClause == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
            }

            key = null;
            EncryptedKeyIdentifierClause encryptedKeyIdentifierClause = keyIdentifierClause as EncryptedKeyIdentifierClause;

            if (encryptedKeyIdentifierClause != null)
            {
                SecurityKeyIdentifier keyIdentifier = encryptedKeyIdentifierClause.EncryptingKeyIdentifier;
                if (keyIdentifier != null && keyIdentifier.Count > 0)
                {
                    for (int i = 0; i < keyIdentifier.Count; i++)
                    {
                        SecurityKey unwrappingSecurityKey = null;
                        if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
                        {
                            byte[] wrappedKey        = encryptedKeyIdentifierClause.GetEncryptedKey();
                            string wrappingAlgorithm = encryptedKeyIdentifierClause.EncryptionMethod;
                            byte[] unwrappedKey      = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
                            key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
                            return(true);
                        }
                    }
                }
            }
            else
            {
                SecurityToken token = null;
                if (TryResolveToken(keyIdentifierClause, out token))
                {
                    if (token.SecurityKeys.Count > 0)
                    {
                        key = token.SecurityKeys[0];
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 35
0
        public static ClaimsPrincipal Validate(string token, InMemorySymmetricSecurityKey signingKey, string issuer, string audience)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            // Parse JWT from the Base64UrlEncoded wire form
            //(<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
            //JwtSecurityToken parsedJwt = tokenHandler.ReadToken(token) as JwtSecurityToken;

            TokenValidationParameters validationParams =
                new TokenValidationParameters()
                {
                    ValidateAudience = true,
                    ValidateIssuer = true,
                    ValidAudience = audience,
                    ValidIssuer = issuer,
                    IssuerSigningKey = signingKey,
                    ValidateLifetime = true
                };

            SecurityToken securityToken = null;

            return tokenHandler.ValidateToken(token, validationParams, out securityToken);
        }
        public void Init()
        {
            DataProtectection.Instance = new NoProtection();
            globalConfiguration = new GlobalConfiguration() { Issuer = "Test Issuer" };

            rocv = new Mock<IResourceOwnerCredentialValidation>();
            config = new Mock<IAuthorizationServerConfiguration>();
            handleManager = new Mock<IStoredGrantManager>();
            assertionGrantValidator = new Mock<IAssertionGrantValidation>();
            clientManager = new Mock<IClientManager>();

            tokenService = new TokenService(globalConfiguration);


            #region Setup Test Client
            string secret = "12345678";
            byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(secret);
            string base64EncodedSecret = Convert.ToBase64String(encodedByte);
            _Client = new Client()
            {
                ClientId = "MobileAppShop",
                ClientSecret = base64EncodedSecret,
                Flow = OAuthFlow.ResourceOwner,
                AllowRefreshToken = true
            };
            #endregion

            #region Setup Test Application
            var scope = new Scope();
            scope.Name = "read";
            scope.AllowedClients = new List<Client>();
            scope.AllowedClients.Add(_Client);
            _Scopes = new List<Scope>();
            _Scopes.Add(scope);

            string symmetricKey = "C33333333333333333333333335=";
            byte[] keybytes = Convert.FromBase64String(symmetricKey);
            SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes);
            _Application = new Application()
            {
                Name = "Test Application 1",
                Scopes = _Scopes,
                Audience = "Test Audience",
                TokenLifetime = 1,
                AllowRefreshToken = true,
            };
            #endregion

            #region Setup Example StoredGrant
            Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") };
            _StoredGrant = new StoredGrant() 
            { 
                GrantId = "MyFavouriteRefrehToken1234",
                CreateRefreshToken = true,
                Client = _Client,
                ResourceOwner = resourceOwnerClaims.ToStoredGrantClaims().ToList(),
                Expiration = DateTime.Now.AddDays(1),
                RefreshTokenExpiration = DateTime.Now.AddMonths(1),
                Type = StoredGrantType.RefreshTokenIdentifier,
                Scopes = _Scopes,
                Application = _Application
            };
            #endregion

            #region Setup Mocking Objects
            // IAuthorizationServerConfiguration
            config.Setup(x => x.FindApplication(It.IsNotNull<string>()))
                .Returns((string name) =>
                {
                    return _Application;
                });
            config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration);

            // IClientManager
            clientManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string clientId) =>
                {
                    return _Client;
                });

            // IResourceOwnerCredentialValidation
            rocv.Setup(x => x.Validate(It.IsNotNull<string>(), It.IsNotNull<string>()))
                .Returns((string username, string password) =>
                {
                    return Principal.Create("Test", resourceOwnerClaims);
                });

            // IStoredGrantManager
            handleManager.Setup(x => x.Get(It.IsNotNull<string>()))
                .Returns((string grantIdentifier) => 
                {
                    return _StoredGrant;
                });

            #endregion

            _TokenController = new TokenController(
                rocv.Object,
                config.Object,
                handleManager.Object,
                assertionGrantValidator.Object,
                tokenService,
                clientManager.Object);
            _TokenController.Request = new HttpRequestMessage();
            _TokenController.Request.SetConfiguration(new HttpConfiguration());
        }
        // hmm, no error
        public void GetSymmetricAlgorithmWrongSize()
        {
            Key key = new Key(new byte [32]);

            Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes192Encryption));
        }
Ejemplo n.º 38
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            var issuer     = "http://localhost:51912/";                                                           //发行者
            var audience   = "fNm0EDIXbfuuDowUpAoq5GTEiywV8eg0TpiIVnV8";                                          //观众
            var secret     = TextEncodings.Base64Url.Decode(OAuthCommon.Constants.Consts.JWT.Security.SecretKey); //秘钥
            var signingKey = new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(secret);

            //令牌验证参数
            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer    = "http://localhost:51912/",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = false,
                ValidAudience    = audience,

                // Validate the token expiry
                ValidateLifetime = true,

                ClockSkew = TimeSpan.Zero
            };

            //配置JwtBearer授权中间件   这个中间件的作用主要是解决由JWT方式提供的身份认证。算是Resource资源,认证服务器需要另外开发
            app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
            {
                TokenValidationParameters = tokenValidationParameters,
                AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active,
                AuthenticationType        = "Bearer",
                AllowedAudiences          = new[] { audience },
                Description = new AuthenticationDescription(),
                Realm       = "",//领域,范围;
                Provider    = new OAuthBearerAuthenticationProvider()
                {
                    //验证当前访客身份
                    OnValidateIdentity = context =>
                    {
                        AuthenticationTicket ticket = context.Ticket;

                        //校验身份是否过期
                        if (ticket.Properties.ExpiresUtc < DateTime.Now)
                        {
                            context.SetError("the token has expired!");
                            context.Rejected();
                        }
                        else
                        {
                            context.Validated(ticket);
                        }
                        return(Task.FromResult <object>(context));
                    },

                    //处理授权令牌 OAuthBearerAuthenticationHandler
                    //headers Authorization=Bear:token
                    OnRequestToken = (context) =>
                    {
                        context.Token = context.Token ?? context.Request.Query["access_token"];
                        if (context.Token != null)
                        {
                            context.Response.Headers["WWW-Authorization"] = "Bearer";
                            //protector
                            IDataProtector protector   = app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1");
                            JwtFormat ticketDataFormat = new JwtFormat(tokenValidationParameters);

                            var ticket           = ticketDataFormat.Unprotect(context.Token);//从令牌字符串中,获取授权票据
                            context.Request.User = new ClaimsPrincipal(ticket.Identity);
                        }
                        return(Task.FromResult <object>(context));
                    },
                    OnApplyChallenge = (context) => { return(Task.FromResult <object>(context)); }
                },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret) //对称加密
                }
            });
        }
		public void GetSymmetricAlgorithm3VulnerableTDESEnc ()
		{
			byte [] bytes = new byte [24];
			Key key = new Key (bytes);
			// strange, TripleDesEncryption works with 32bytes key,
			// but TripleDesKeyWrap doesn't.
			key.GetSymmetricAlgorithm (SecurityAlgorithms.TripleDesEncryption);
		}
Ejemplo n.º 40
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Check.IsNotNull(request, "request");
            HttpStatusCode statusCode;
            string token;
          
            if (request.RequestUri.AbsolutePath.Contains("/authenticate"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/signout"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/SignOutCallback"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("/windowsLiveAuthorization"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("api/GetSupportedIdentityProviders"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (request.RequestUri.AbsolutePath.Contains("api/SignInCallBack"))
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (!TryRetrieveToken(request, out token))
            {
                statusCode = HttpStatusCode.Unauthorized;
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
            }

            try
            {
                diagnostics.WriteInformationTrace(TraceEventId.Flow, "Validating bearer token: {0}", token);

                string issuersValue = ConfigurationManager.AppSettings["Issuers"];
                string signingSymmetricKey = ConfigurationManager.AppSettings["SigningSymmetricKey"];
                string allowedAudience = ConfigurationManager.AppSettings["AllowedAudience"];

                // Use JWTSecurityTokenHandler to validate the JWT token
                ApiJWTSecurityTokenHandler tokenHandler = new ApiJWTSecurityTokenHandler();

                List<string> issuers = new List<string>();
                issuers.AddRange(issuersValue.Split(new[] { ',' }));

                InMemorySymmetricSecurityKey securityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(signingSymmetricKey));

                NamedKeySecurityToken namedToken = new NamedKeySecurityToken(allowedAudience, new List<SecurityKey>() { securityKey });

                // Set the expected properties of the JWT token in the TokenValidationParameters
                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = allowedAudience,
                    ValidIssuers = issuers,
                    SigningToken = namedToken
                };

                ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters);
                ClaimsIdentity claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
                try
                {
                    IUserService userService = (IUserService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IUserService));
                    User user = IdentityHelper.GetCurrentUser(userService, claimsPrincipal);
                    foreach (var role in user.UserRoles)
                    {
                        if (!claimsIdentity.HasClaim(ClaimTypes.Role, role.Role.Name))
                        {
                            claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Role.Name));
                        }
                    }
                }
                catch (UserNotFoundException)
                {
                    // No need to do anything here because GetUsersByNameIdentifier action in UsersController will take care of sending appropriate http response.
                }

                Thread.CurrentPrincipal = claimsPrincipal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = claimsPrincipal;
                }

                diagnostics.WriteInformationTrace(TraceEventId.Flow,
                                        "Authorization token validated successfully");

                return base.SendAsync(request, cancellationToken);
            }
            catch (SecurityTokenValidationException secutiryTokenValidationException)
            {
                FederatedAuthentication.WSFederationAuthenticationModule.SignOut(true);
                HttpResponseMessage response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, secutiryTokenValidationException);
                return Task<HttpResponseMessage>.Factory.StartNew(() => response);
            }
        }
Ejemplo n.º 41
0
        static string JWToken()
        {
            var domain = "http://localhost";
            var allowedAudience = "http://localhost:10100";
            var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
            var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
            var issuer = "PareidoliaSW";

            var securityKey = Convert.FromBase64String(mainKey);
            var inMemKey = new InMemorySymmetricSecurityKey(securityKey);

            var now = DateTime.UtcNow;
            var expiry = now.AddHours(8);
            var tokenHandler = new JwtSecurityTokenHandler();
            var claimsList = new List<Claim>()
            {
                new Claim(ClaimTypes.Webpage, allowedAudience),
                new Claim(ClaimTypes.Uri, domain),
                new Claim(ClaimTypes.Expiration,expiry.Ticks.ToString()),
                new Claim("scope", "WebBridge")
            };
            //var roles = new List<string>() { "admin" };
            //claimsList.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

            //var identity = new GenericIdentity("user");

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claimsList),
                TokenIssuerName = issuer,
                AppliesToAddress = allowedAudience,
                Lifetime = new Lifetime(now, expiry),
                SigningCredentials = new SigningCredentials(inMemKey, signatureAlgorithm, digestAlgorithm),
            };

            var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

            return token;
        }
        public static TokenResult GetTestToken(IAsset MyAsset, CloudMediaContext _context, ContentKeyType? keytype = null, SigningCredentials signingcredentials = null, string optionid = null, bool displayUI = false)
        {

            TokenResult MyResult = new TokenResult();

            /// WITH UI
            if (displayUI)
            {
                CreateTestToken form = new CreateTestToken(MyAsset, _context, keytype, optionid) { StartDate = DateTime.Now.AddMinutes(-5), EndDate = DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration) };
                if (form.ShowDialog() == DialogResult.OK)
                {

                    if (form.GetOption != null)
                    {
                        string tokenTemplateString = form.GetOption.Restrictions.FirstOrDefault().Requirements;
                        if (!string.IsNullOrEmpty(tokenTemplateString))
                        {
                            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(form.GetContentKeyFromSelectedOption.Id);
                            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                            if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                            {
                                MyResult.TokenType = tokenTemplate.TokenType;
                                MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                MyResult.ContentKeyType = form.GetContentKeyFromSelectedOption.ContentKeyType;

                                if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                {
                                    MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, form.EndDate);

                                }
                                else // JWT
                                {
                                    IList<Claim> myclaims = null;
                                    myclaims = form.GetTokenRequiredClaims;
                                    if (form.PutContentKeyIdentifier)
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                                    if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                    {
                                        InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                        signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                    }
                                    else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                    {
                                        X509Certificate2 cert = form.GetX509Certificate;
                                        if (cert != null) signingcredentials = new X509SigningCredentials(cert);
                                    }
                                    JwtSecurityToken token = new JwtSecurityToken(issuer: form.GetIssuerUri, audience: form.GetAudienceUri, notBefore: form.StartDate, expires: form.EndDate, signingCredentials: signingcredentials, claims: myclaims);
                                    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                    MyResult.TokenString = handler.WriteToken(token);
                                }
                            }
                        }
                    }
                }
            }
            /////////////////////////////// NO UI
            else if (keytype != null)
            {

                IContentKey key = MyAsset.ContentKeys.Where(k => k.ContentKeyType == keytype).FirstOrDefault();
                if (key != null && key.AuthorizationPolicyId != null)
                {
                    IContentKeyAuthorizationPolicy policy = _context.ContentKeyAuthorizationPolicies.Where(p => p.Id == key.AuthorizationPolicyId).FirstOrDefault();
                    if (policy != null)
                    {
                        IContentKeyAuthorizationPolicyOption option = null;
                        if (optionid == null) // user does not want a specific option
                        {
                            option = policy.Options.Where(o => (ContentKeyRestrictionType)o.Restrictions.FirstOrDefault().KeyRestrictionType == ContentKeyRestrictionType.TokenRestricted).FirstOrDefault();
                        }
                        else
                        {
                            option = policy.Options.Where(o => o.Id == optionid).FirstOrDefault(); // user wants a token for a specific option
                        }

                        if (option != null) // && option.Restrictions.FirstOrDefault() != null && option.Restrictions.FirstOrDefault().KeyRestrictionType == (int)ContentKeyRestrictionType.TokenRestricted)
                        {
                            string tokenTemplateString = option.Restrictions.FirstOrDefault().Requirements;
                            if (!string.IsNullOrEmpty(tokenTemplateString))
                            {
                                Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(key.Id);
                                TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer.Deserialize(tokenTemplateString);

                                if (tokenTemplate.OpenIdConnectDiscoveryDocument == null)
                                {
                                    MyResult.TokenType = tokenTemplate.TokenType;
                                    MyResult.IsTokenKeySymmetric = (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey));
                                    MyResult.ContentKeyType = (ContentKeyType)keytype;

                                    if (tokenTemplate.TokenType == TokenType.SWT) //SWT
                                    {
                                        MyResult.TokenString = TokenRestrictionTemplateSerializer.GenerateTestToken(tokenTemplate, null, rawkey, DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration));
                                    }
                                    else // JWT
                                    {
                                        List<Claim> myclaims = null;
                                        myclaims = new List<Claim>();
                                        myclaims.Add(new Claim(TokenClaim.ContentKeyIdentifierClaimType, rawkey.ToString()));

                                        if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(SymmetricVerificationKey))
                                        {
                                            InMemorySymmetricSecurityKey tokenSigningKey = new InMemorySymmetricSecurityKey((tokenTemplate.PrimaryVerificationKey as SymmetricVerificationKey).KeyValue);
                                            signingcredentials = new SigningCredentials(tokenSigningKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
                                        }
                                        else if (tokenTemplate.PrimaryVerificationKey.GetType() == typeof(X509CertTokenVerificationKey))
                                        {
                                            if (signingcredentials == null)
                                            {
                                                X509Certificate2 cert = DynamicEncryption.GetCertificateFromFile(true);
                                                if (cert != null) signingcredentials = new X509SigningCredentials(cert);
                                            }
                                        }
                                        JwtSecurityToken token = new JwtSecurityToken(issuer: tokenTemplate.Issuer, audience: tokenTemplate.Audience, notBefore: DateTime.Now.AddMinutes(-5), expires: DateTime.Now.AddMinutes(Properties.Settings.Default.DefaultTokenDuration), signingCredentials: signingcredentials, claims: myclaims);
                                        JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                                        MyResult.TokenString = handler.WriteToken(token);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return MyResult;
        }
        public void GetSymmetricAlgorithmNullKey()
        {
            Key key = new Key(raw);

            Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.Aes192Encryption));
        }
            protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
            {
                if (keyIdentifierClause == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");

                key = null;
                for (int i = 0; i < this.tokens.Count; ++i)
                {
                    SecurityKey securityKey = this.tokens[i].ResolveKeyIdentifierClause(keyIdentifierClause);
                    if (securityKey != null)
                    {
                        key = securityKey;
                        return true;
                    }
                }

                if (keyIdentifierClause is EncryptedKeyIdentifierClause)
                {
                    EncryptedKeyIdentifierClause keyClause = (EncryptedKeyIdentifierClause)keyIdentifierClause;
                    SecurityKeyIdentifier keyIdentifier = keyClause.EncryptingKeyIdentifier;
                    if (keyIdentifier != null && keyIdentifier.Count > 0)
                    {
                        for (int i = 0; i < keyIdentifier.Count; i++)
                        {
                            SecurityKey unwrappingSecurityKey = null;
                            if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
                            {
                                byte[] wrappedKey = keyClause.GetEncryptedKey();
                                string wrappingAlgorithm = keyClause.EncryptionMethod;
                                byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
                                key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
                                return true;
                            }
                        }
                    }
                }

                return key != null;
            }
		XmlElement VerifyInput2 (MessageBuffer buf)
		{
			Message msg2 = buf.CreateMessage ();
			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter (XmlWriter.Create (sw))) {
				msg2.WriteMessage (w);
			}
			XmlDocument doc = new XmlDocument ();
			doc.PreserveWhitespace = true;
			doc.LoadXml (sw.ToString ());

			// decrypt the key with service certificate privkey
			PaddingMode mode = PaddingMode.PKCS7; // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
			EncryptedXml encXml = new EncryptedXml (doc);
			encXml.Padding = mode;
			X509Certificate2 cert2 = new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
			nsmgr.AddNamespace ("s", "http://www.w3.org/2003/05/soap-envelope");
			nsmgr.AddNamespace ("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
			nsmgr.AddNamespace ("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
			nsmgr.AddNamespace ("e", "http://www.w3.org/2001/04/xmlenc#");
			nsmgr.AddNamespace ("dsig", "http://www.w3.org/2000/09/xmldsig#");
			XmlNode n = doc.SelectSingleNode ("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: enckey does not exist");
			string raw = n.InnerText;
			byte [] rawbytes = Convert.FromBase64String (raw);
			RSACryptoServiceProvider rsa = (RSACryptoServiceProvider) cert2.PrivateKey;
			byte [] decryptedKey = EncryptedXml.DecryptKey (rawbytes, rsa, true);//rsa.Decrypt (rawbytes, true);

#if false
			// create derived keys
			Dictionary<string,byte[]> keys = new Dictionary<string,byte[]> ();
			InMemorySymmetricSecurityKey skey =
				new InMemorySymmetricSecurityKey (decryptedKey);
			foreach (XmlElement el in doc.SelectNodes ("//o:Security/c:DerivedKeyToken", nsmgr)) {
				n = el.SelectSingleNode ("c:Offset", nsmgr);
				int offset = (n == null) ? 0 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Length", nsmgr);
				int length = (n == null) ? 32 :
					int.Parse (n.InnerText, CultureInfo.InvariantCulture);
				n = el.SelectSingleNode ("c:Label", nsmgr);
				byte [] label = (n == null) ? decryptedKey :
					Convert.FromBase64String (n.InnerText);
				n = el.SelectSingleNode ("c:Nonce", nsmgr);
				byte [] nonce = (n == null) ? new byte [0] :
					Convert.FromBase64String (n.InnerText);
				byte [] derkey = skey.GenerateDerivedKey (
					//SecurityAlgorithms.Psha1KeyDerivation,
					"http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
					label,
					nonce,
					length * 8,
					offset);

				keys [el.GetAttribute ("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
			}
#endif

			// decrypt the signature with the decrypted key
#if true
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;
			MemoryStream ms = new MemoryStream ();
			CryptoStream cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedSignature = ms.ToArray ();
#else
			Rijndael aes = RijndaelManaged.Create ();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			aes.Mode = CipherMode.CBC;
			aes.Padding = mode;

			EncryptedData ed = new EncryptedData ();
			n = doc.SelectSingleNode ("//o:Security/e:EncryptedData", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			ed.LoadXml (n as XmlElement);
			byte [] decryptedSignature = encXml.DecryptData (ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

			// decrypt the body with the decrypted key
#if true
			n = doc.SelectSingleNode ("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
			Assert.IsNotNull (n, "premise: encdata does not exist");
			raw = n.InnerText;
			rawbytes = Convert.FromBase64String (raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			ms = new MemoryStream ();
			cs = new CryptoStream (ms, aes.CreateDecryptor (), CryptoStreamMode.Write);
			cs.Write (rawbytes, 0, rawbytes.Length);
			cs.Close ();
			byte [] decryptedBody = ms.ToArray ();
#else
			// decrypt the body with the decrypted key
			EncryptedData ed2 = new EncryptedData ();
			XmlElement el = doc.SelectSingleNode ("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
			ed2.LoadXml (el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
			aes.Key = decryptedKey;
			byte [] decryptedBody = encXml.DecryptData (ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedBody));
Console.Error.WriteLine ("============= Decrypted Body End ===========");

			// FIXME: find out what first 16 bytes mean.
			for (int mmm = 0; mmm < 16; mmm++) decryptedBody [mmm] = 0x20;
			doc.LoadXml (Encoding.UTF8.GetString (decryptedBody));
			Assert.AreEqual ("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
			Assert.AreEqual ("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

			return doc.DocumentElement;
		}
        public void GetSymmetricAlgorithmWrongSizeDES()
        {
            Key key = new Key(new byte [32]);

            Assert.IsNotNull(key.GetSymmetricAlgorithm(SecurityAlgorithms.TripleDesKeyWrap));
        }
 protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
 {
     if (keyIdentifierClause == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
     }
     key = null;
     for (int i = 0; i < this.tokens.Count; i++)
     {
         SecurityKey key2 = this.tokens[i].ResolveKeyIdentifierClause(keyIdentifierClause);
         if (key2 != null)
         {
             key = key2;
             return true;
         }
     }
     if (keyIdentifierClause is EncryptedKeyIdentifierClause)
     {
         EncryptedKeyIdentifierClause clause = (EncryptedKeyIdentifierClause) keyIdentifierClause;
         SecurityKeyIdentifier encryptingKeyIdentifier = clause.EncryptingKeyIdentifier;
         if ((encryptingKeyIdentifier != null) && (encryptingKeyIdentifier.Count > 0))
         {
             for (int j = 0; j < encryptingKeyIdentifier.Count; j++)
             {
                 SecurityKey key3 = null;
                 if (base.TryResolveSecurityKey(encryptingKeyIdentifier[j], out key3))
                 {
                     byte[] encryptedKey = clause.GetEncryptedKey();
                     string encryptionMethod = clause.EncryptionMethod;
                     byte[] symmetricKey = key3.DecryptKey(encryptionMethod, encryptedKey);
                     key = new InMemorySymmetricSecurityKey(symmetricKey, false);
                     return true;
                 }
             }
         }
     }
     return (key != null);
 }
        public ConfigurationBasedIssuerTokenResolver(XmlNodeList customConfiguration)
        {
            this.keys = new Dictionary<string, SecurityKey>();
            if (customConfiguration == null)
            {
                throw new ArgumentNullException("customConfiguration");
            }

            List<XmlElement> xmlElements = GetXmlElements(customConfiguration);
            if (xmlElements.Count != 1)
            {
                throw new InvalidOperationException("There should be only one xml element as the configuration of this class");
            }

            XmlElement element = xmlElements[0];
            if (!StringComparer.Ordinal.Equals(element.LocalName, "serviceKeys"))
            {
                throw new InvalidOperationException("The top element of the configuration should be named 'serviceKeys'");
            }

            foreach (XmlNode node in element.ChildNodes)
            {
                XmlElement addRemoveNode = node as XmlElement;
                if (addRemoveNode != null)
                {
                    if (StringComparer.Ordinal.Equals(addRemoveNode.LocalName, "add"))
                    {
                        XmlNode serviceNameNode = addRemoveNode.Attributes.GetNamedItem("serviceName");
                        XmlNode serviceKeyNode = addRemoveNode.Attributes.GetNamedItem("serviceKey");
                        if (((addRemoveNode.Attributes.Count != 2) || (serviceNameNode == null)) || ((serviceKeyNode == null) || string.IsNullOrEmpty(serviceKeyNode.Value)))
                        {
                            throw new InvalidOperationException("The <add> element is malformed. The right format is: <add serviceName=\"name\" serviceKey=\"base64Key\"");
                        }

                        string serviceName = serviceNameNode.Value.ToLowerInvariant();
                        string serviceKey = string.Intern(serviceKeyNode.Value);
                        var serviceKeySecurityKey = new InMemorySymmetricSecurityKey(Convert.FromBase64String(serviceKey));
                        this.keys.Add(serviceName, serviceKeySecurityKey);
                    }
                    else if (StringComparer.Ordinal.Equals(addRemoveNode.LocalName, "remove"))
                    {
                        if ((addRemoveNode.Attributes.Count != 1) || !StringComparer.Ordinal.Equals(addRemoveNode.Attributes[0].LocalName, "serviceName"))
                        {
                            throw new InvalidOperationException("The <remove> node should have a serviceName attribute");
                        }

                        string serviceName = addRemoveNode.Attributes.GetNamedItem("serviceName").Value;
                        this.keys.Remove(serviceName);
                    }
                    else
                    {
                        if (!StringComparer.Ordinal.Equals(addRemoveNode.LocalName, "clear"))
                        {
                            throw new InvalidOperationException(string.Format("Invalid element: {0}", addRemoveNode.LocalName));
                        }

                        this.keys.Clear();
                    }
                }
            }
        }
        /// <summary>
        /// Resolves the given SecurityKeyIdentifierClause to a SecurityKey.
        /// </summary>
        /// <param name="keyIdentifierClause">SecurityKeyIdentifierClause to resolve</param>
        /// <param name="key">The resolved SecurityKey.</param>
        /// <returns>True if successfully resolved.</returns>
        /// <exception cref="ArgumentNullException">The input argument 'keyIdentifierClause' is null.</exception>
        protected override bool TryResolveSecurityKeyCore(SecurityKeyIdentifierClause keyIdentifierClause, out SecurityKey key)
        {
            if (keyIdentifierClause == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifierClause");
            }

            key = null;
            EncryptedKeyIdentifierClause encryptedKeyIdentifierClause = keyIdentifierClause as EncryptedKeyIdentifierClause;
            if (encryptedKeyIdentifierClause != null)
            {
                SecurityKeyIdentifier keyIdentifier = encryptedKeyIdentifierClause.EncryptingKeyIdentifier;
                if (keyIdentifier != null && keyIdentifier.Count > 0)
                {
                    for (int i = 0; i < keyIdentifier.Count; i++)
                    {
                        SecurityKey unwrappingSecurityKey = null;
                        if (TryResolveSecurityKey(keyIdentifier[i], out unwrappingSecurityKey))
                        {
                            byte[] wrappedKey = encryptedKeyIdentifierClause.GetEncryptedKey();
                            string wrappingAlgorithm = encryptedKeyIdentifierClause.EncryptionMethod;
                            byte[] unwrappedKey = unwrappingSecurityKey.DecryptKey(wrappingAlgorithm, wrappedKey);
                            key = new InMemorySymmetricSecurityKey(unwrappedKey, false);
                            return true;
                        }
                    }
                }
            }
            else
            {
                SecurityToken token = null;
                if (TryResolveToken(keyIdentifierClause, out token))
                {
                    if (token.SecurityKeys.Count > 0)
                    {
                        key = token.SecurityKeys[0];
                        return true;
                    }
                }
            }

            return false;
        }