/// <summary>
        /// Validates the client secret
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="secret">The client secret.</param>
        /// <returns></returns>
        public virtual Task <bool> ValidateClientSecretAsync(Client client, string secret)
        {
            var secretSha256 = secret.Sha256();
            var secretSha512 = secret.Sha512();

            foreach (var clientSecret in client.ClientSecrets)
            {
                bool   isValid = false;
                byte[] clientSecretBytes;

                // check if client secret is still valid
                if (clientSecret.Expiration.HasExpired())
                {
                    continue;
                }

                try
                {
                    clientSecretBytes = Convert.FromBase64String(clientSecret.Value);
                }
                catch (FormatException)
                {
                    // todo: logging
                    throw new InvalidOperationException("Invalid hashing algorithm for client secret.");
                }

                if (clientSecretBytes.Length == 32)
                {
                    isValid = ObfuscatingComparer.IsEqual(clientSecret.Value, secretSha256);
                }
                else if (clientSecretBytes.Length == 64)
                {
                    isValid = ObfuscatingComparer.IsEqual(clientSecret.Value, secretSha512);
                }
                else
                {
                    // todo: logging
                    throw new InvalidOperationException("Invalid hashing algorithm for client secret.");
                }

                if (isValid)
                {
                    return(Task.FromResult(true));
                }
            }

            return(Task.FromResult(false));
        }
        private static void TestConstant(string x, string y, string z)
        {
            var sw1 = Stopwatch.StartNew();

            for (int i = 0; i < iterations; i++)
            {
                bool same = ObfuscatingComparer.IsEqual(x, y);
            }
            Console.WriteLine("Same String: {0}", sw1.ElapsedMilliseconds);
            sw1.Stop();

            var sw2 = Stopwatch.StartNew();

            for (int i = 0; i < iterations; i++)
            {
                bool same = ObfuscatingComparer.IsEqual(x, z);
            }
            Console.WriteLine("Different String: {0}", sw2.ElapsedMilliseconds);
            sw2.Stop();
        }
Beispiel #3
0
        protected virtual void VerifySignature(JsonWebToken jwt, SecurityKey signingKey)
        {
            var key = signingKey as InMemorySymmetricSecurityKey;

            if (key == null)
            {
                throw new SecurityTokenValidationException("Unsupported signing key.");
            }

            string verifySignature;

            using (var algorithm = key.GetKeyedHashAlgorithm(ValidateHmacAlgorithm(key.KeySize, jwt.Header.SignatureAlgorithm)))
            {
                verifySignature = Base64Url.Encode(algorithm.ComputeHash(Encoding.UTF8.GetBytes(jwt.UnsignedToken)));
            }

            if (!(ObfuscatingComparer.IsEqual(verifySignature, jwt.Signature)))
            {
                throw new SecurityTokenValidationException("Invalid signature.");
            }
        }
Beispiel #4
0
        /// <summary>
        /// Verifies the signature of the token.
        /// </summary>
        /// <param name="key">The key used for signing.</param>
        /// <returns>true if the signatures match, false otherwise.</returns>
        public bool VerifySignature(byte[] key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (_signature == null || _unsignedString == null)
            {
                throw new InvalidOperationException("Token has never been signed");
            }

            string verifySignature;

            using (HMACSHA256 signatureAlgorithm = new HMACSHA256(key))
            {
                verifySignature = Convert.ToBase64String(signatureAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(_unsignedString)));
            }

            return(ObfuscatingComparer.IsEqual(verifySignature, _signature));
        }
Beispiel #5
0
        /// <summary>
        /// Validates the client secret
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="secret">The client secret.</param>
        /// <returns></returns>
        public virtual Task <bool> ValidateClientSecretAsync(Client client, string secret)
        {
            foreach (var clientSecret in client.ClientSecrets)
            {
                // check if client secret is still valid
                if (clientSecret.Expiration.HasExpired())
                {
                    continue;
                }

                // use time constant string comparison
                var isValid = ObfuscatingComparer.IsEqual(clientSecret.Value, secret);

                if (isValid)
                {
                    return(Task.FromResult(true));
                }
            }

            return(Task.FromResult(false));
        }
        public async Task <Client> ValidateClientCredentialsAsync(ClientCredential credential)
        {
            if (credential == null || credential.ClientId == null || credential.Secret == null)
            {
                throw new InvalidOperationException("credential is null");
            }

            var client = await _clients.FindClientByIdAsync(credential.ClientId);

            if (client == null || client.Enabled == false)
            {
                Logger.Error("Client not found in registry or not enabled: " + credential.ClientId);
                return(null);
            }

            if (!ObfuscatingComparer.IsEqual(client.ClientSecret, credential.Secret))
            {
                Logger.Error("Invalid client secret: " + client.ClientId);
                return(null);
            }

            Logger.InfoFormat("Client found in registry: {0} / {1}", client.ClientId, client.ClientName);
            return(client);
        }
        public static AuthenticationConfiguration CreateConfiguration()
        {
            var config = new AuthenticationConfiguration
            {
                DefaultAuthenticationScheme = "Basic",
            };

            #region Basic Authentication
            config.AddBasicAuthentication((userName, password) => userName == password);
            #endregion

            #region SimpleWebToken
            config.AddSimpleWebToken(
                "http://identity.thinktecture.com/trust",
                Constants.Realm,
                Constants.IdSrvSymmetricSigningKey,
                AuthenticationOptions.ForAuthorizationHeader("IdSrv"));
            #endregion

            #region JsonWebToken
            config.AddJsonWebToken(
                "http://selfissued.test",
                Constants.Realm,
                Constants.IdSrvSymmetricSigningKey,
                AuthenticationOptions.ForAuthorizationHeader("JWT"));
            #endregion

            #region IdentityServer SAML
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            idsrvRegistry.AddTrustedIssuer("A1EED7897E55388FCE60FEF1A1EED81FF1CBAEC6", "Thinktecture IdSrv");

            var idsrvConfig = new SecurityTokenHandlerConfiguration();
            idsrvConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            idsrvConfig.IssuerNameRegistry   = idsrvRegistry;
            idsrvConfig.CertificateValidator = X509CertificateValidator.None;

            config.AddSaml2(idsrvConfig, AuthenticationOptions.ForAuthorizationHeader("IdSrvSaml"));
            #endregion

            #region ACS SWT
            config.AddSimpleWebToken(
                "https://" + Constants.ACS + "/",
                Constants.Realm,
                Constants.AcsSymmetricSigningKey,
                AuthenticationOptions.ForAuthorizationHeader("ACS"));
            #endregion

            #region AccessKey
            var handler = new SimpleSecurityTokenHandler("my access key", token =>
            {
                if (ObfuscatingComparer.IsEqual(token, "accesskey123"))
                {
                    return(new ClaimsIdentity(new Claim[]
                    {
                        new Claim("customerid", "123")
                    }, "Custom"));
                }

                return(null);
            });

            config.AddAccessKey(handler, AuthenticationOptions.ForQueryString("key"));
            #endregion

            return(config);
        }
        public static AuthenticationConfiguration CreateConfiguration()
        {
            var config = new AuthenticationConfiguration
            {
                DefaultAuthenticationScheme = "Basic",
                EnableSessionToken          = true
            };

            #region BasicAuthentication
            config.AddBasicAuthentication((userName, password) => userName == password, retainPassword: false);
            #endregion

            #region SimpleWebToken
            config.AddSimpleWebToken(
                issuer: Constants.IdSrvIssuerName,
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("IdSrv"));
            #endregion

            #region JsonWebToken
            config.AddJsonWebToken(
                issuer: "http://selfissued.test",
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("JWT"));
            #endregion

            #region JsonWebToken Windows Store Client
            config.AddJsonWebToken(
                issuer: "http://identityserver.v2.thinktecture.com/trust/changethis",
                audience: "https://test/rp/",
                signingKey: "3ihK5qGVhp8ptIk9+TDucXQW4Aaengg3d5m6gU8nzc8=",
                options: AuthenticationOptions.ForAuthorizationHeader("Win8"));
            #endregion

            #region IdentityServer SAML
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            idsrvRegistry.AddTrustedIssuer(Constants.IdSrvSamlSigningKeyThumbprint, "Thinktecture IdSrv");

            var idsrvConfig = new SecurityTokenHandlerConfiguration();
            idsrvConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            idsrvConfig.IssuerNameRegistry   = idsrvRegistry;
            idsrvConfig.CertificateValidator = X509CertificateValidator.None;

            config.AddSaml2(idsrvConfig, AuthenticationOptions.ForAuthorizationHeader("IdSrvSaml"));
            #endregion

            #region ADFS SAML
            var adfsRegistry = new ConfigurationBasedIssuerNameRegistry();
            adfsRegistry.AddTrustedIssuer(Constants.AdfsSamlSigningKeyThumbprint, "ADFS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            adfsConfig.IssuerNameRegistry   = adfsRegistry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            config.AddSaml2(adfsConfig, AuthenticationOptions.ForAuthorizationHeader("AdfsSaml"));
            #endregion

            #region ACS SWT
            config.AddSimpleWebToken(
                issuer: "https://" + Constants.ACS + "/",
                audience: Constants.Realm,
                signingKey: Constants.AcsSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("ACS"));
            #endregion

            #region AccessKey
            config.AddAccessKey(token =>
            {
                if (ObfuscatingComparer.IsEqual(token, "accesskey123"))
                {
                    return(Principal.Create("Custom",
                                            new Claim("customerid", "123"),
                                            new Claim("email", "*****@*****.**")));
                }

                return(null);
            }, AuthenticationOptions.ForQueryString("key"));
            #endregion

            #region Client Certificate
            config.AddClientCertificate(
                ClientCertificateMode.ChainValidationWithIssuerSubjectName,
                "CN=PortableCA");
            #endregion

            return(config);
        }
        public static AuthenticationConfiguration CreateConfiguration()
        {
            var config = new AuthenticationConfiguration
            {
                DefaultAuthenticationScheme = "Basic",
                EnableSessionToken          = true
            };

            #region BasicAuthentication
            config.AddBasicAuthentication((userName, password) => userName == password, retainPassword: false);
            #endregion

            #region SimpleWebToken
            config.AddSimpleWebToken(
                issuer: "http://identity.thinktecture.com/trust",
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("IdSrv"));
            #endregion

            #region JsonWebToken
            config.AddJsonWebToken(
                issuer: "http://selfissued.test",
                audience: Constants.Realm,
                signingKey: Constants.IdSrvSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("JWT"));
            #endregion

            #region IdentityServer SAML
            var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry();
            idsrvRegistry.AddTrustedIssuer("A1EED7897E55388FCE60FEF1A1EED81FF1CBAEC6", "Thinktecture IdSrv");

            var idsrvConfig = new SecurityTokenHandlerConfiguration();
            idsrvConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            idsrvConfig.IssuerNameRegistry   = idsrvRegistry;
            idsrvConfig.CertificateValidator = X509CertificateValidator.None;

            config.AddSaml2(idsrvConfig, AuthenticationOptions.ForAuthorizationHeader("IdSrvSaml"));
            #endregion

            #region ADFS SAML
            var adfsRegistry = new ConfigurationBasedIssuerNameRegistry();
            adfsRegistry.AddTrustedIssuer("8EC7F962CC083FF7C5997D8A4D5ED64B12E4C174", "ADFS");
            adfsRegistry.AddTrustedIssuer("b6 93 46 34 7f 70 a9 c3 72 02 18 ae f1 82 2a 5c 97 b1 8c a5", "PETS ADFS");

            var adfsConfig = new SecurityTokenHandlerConfiguration();
            adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm));
            adfsConfig.IssuerNameRegistry   = adfsRegistry;
            adfsConfig.CertificateValidator = X509CertificateValidator.None;

            config.AddSaml2(adfsConfig, AuthenticationOptions.ForAuthorizationHeader("AdfsSaml"));
            #endregion

            #region ACS SWT
            config.AddSimpleWebToken(
                issuer: "https://" + Constants.ACS + "/",
                audience: Constants.Realm,
                signingKey: Constants.AcsSymmetricSigningKey,
                options: AuthenticationOptions.ForAuthorizationHeader("ACS"));
            #endregion

            #region AccessKey
            config.AddAccessKey(token =>
            {
                if (ObfuscatingComparer.IsEqual(token, "accesskey123"))
                {
                    return(Principal.Create("Custom",
                                            new Claim("customerid", "123"),
                                            new Claim("email", "*****@*****.**")));
                }

                return(null);
            }, AuthenticationOptions.ForQueryString("key"));
            #endregion

            #region Client Certificate
            config.AddClientCertificate(
                ClientCertificateMode.ChainValidationWithIssuerSubjectName,
                "CN=PortableCA");
            #endregion

            return(config);
        }
        public bool ValidatePassword(string password, string hash, string salt)
        {
            var calculatedHash = HashPasswordWithSalt(password, salt);

            return(ObfuscatingComparer.IsEqual(hash, calculatedHash));
        }