public void CreateAndValidateTokens_MultipleX5C()
        {
            List<string> errors = new List<string>();
            var handler = new JwtSecurityTokenHandler();
            var payload = new JwtPayload();
            var header = new JwtHeader();

            payload.AddClaims(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer));
            List<string> x5cs = new List<string> { "x5c1", "x5c2" };
            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            var jwtToken = new JwtSecurityToken(header, payload);
            var jwt = handler.WriteToken(jwtToken);

            var validationParameters =
                new TokenValidationParameters
                {
                    RequireExpirationTime = false,
                    RequireSignedTokens = false,
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ValidateLifetime = false,
                };

            SecurityToken validatedSecurityToken = null;
            var cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            JwtSecurityToken validatedJwt = validatedSecurityToken as JwtSecurityToken;
            object x5csInHeader = validatedJwt.Header[JwtHeaderParameterNames.X5c];
            if (x5csInHeader == null)
            {
                errors.Add("1: validatedJwt.Header[JwtHeaderParameterNames.X5c]");
            }
            else
            {
                var list = x5csInHeader as IEnumerable<object>;
                if ( list == null )
                {
                    errors.Add("2: var list = x5csInHeader as IEnumerable<object>; is NULL.");
                }

                int num = 0;
                foreach(var str in list)
                {
                    num++;
                    if (!(str is string))
                    {
                        errors.Add("3: str is not string, is:" + str.ToString());
                    }
                }

                if (num != x5cs.Count)
                {
                    errors.Add("4: num != x5cs.Count. num: " + num.ToString() + "x5cs.Count: " + x5cs.Count.ToString());
                }
            }

            // make sure we can still validate with existing logic.
            header = new JwtHeader(KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2);
            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            jwtToken = new JwtSecurityToken(header, payload);
            jwt = handler.WriteToken(jwtToken);

            validationParameters.IssuerSigningToken = KeyingMaterial.DefaultAsymmetricX509Token_2048;
            validationParameters.RequireSignedTokens = true;
            validatedSecurityToken = null;
            cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors);
        }
Пример #2
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            if (header is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.header);
            }

            var         contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey);
            Span <byte> buffer = stackalloc byte[_saltSizeInBytes + 1 + _algorithmNameLength];

            _saltGenerator.Generate(buffer.Slice(_algorithmNameLength + 1));
            buffer[_algorithmNameLength] = 0x00;
            _algorithm.EncodedUtf8Bytes.CopyTo(buffer);

            Span <byte> derivedKey = stackalloc byte[_keySizeInBytes];

            Pbkdf2.DeriveKey(_password, buffer, _hashAlgorithm, _iterationCount, derivedKey);

            Span <byte> salt    = buffer.Slice(_algorithmNameLength + 1, _saltSizeInBytes);
            Span <byte> b64Salt = stackalloc byte[Base64Url.GetArraySizeRequiredToEncode(salt.Length)];

            Base64Url.Encode(salt, b64Salt);
            header.Add(JwtHeaderParameterNames.P2s, Utf8.GetString(b64Salt));
            header.Add(JwtHeaderParameterNames.P2c, _iterationCount);

            using var keyWrapper = new AesKeyWrapper(derivedKey, EncryptionAlgorithm, _keyManagementAlgorithm);
            return(keyWrapper.WrapKey(contentEncryptionKey, header, destination));
        }
Пример #3
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            var         cek   = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey);
            Span <byte> nonce = stackalloc byte[IVSize];

            RandomNumberGenerator.Fill(nonce);

            Span <byte> tag = stackalloc byte[TagSize];

            using (var aesGcm = new AesGcm(_key.K))
            {
                var keyBytes = cek.AsSpan();
                if (destination.Length > keyBytes.Length)
                {
                    destination = destination.Slice(0, keyBytes.Length);
                }

                aesGcm.Encrypt(nonce, keyBytes, destination, tag);

                Span <byte> nonceB64 = stackalloc byte[IVB64Size];
                Base64Url.Encode(nonce, nonceB64);
                header.Add(JwtHeaderParameterNames.IV, Utf8.GetString(nonceB64));

                Span <byte> tagB64 = stackalloc byte[TagB64Size];
                Base64Url.Encode(tag, tagB64);
                header.Add(JwtHeaderParameterNames.Tag, Utf8.GetString(tagB64));
            }

            return(cek);
        }
Пример #4
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            if (header is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.header);
            }

            var contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey);
            int bufferSize           = _saltSizeInBytes + _algorithmNameLength + 1;

            byte[]? bufferToReturn = null;
            Span <byte> buffer = bufferSize > Pbkdf2.SaltSizeThreshold + 18 + 1  // 18 = max alg name length
              ? (bufferToReturn = ArrayPool <byte> .Shared.Rent(bufferSize))
              : stackalloc byte[Pbkdf2.SaltSizeThreshold + 18 + 1];

            buffer = buffer.Slice(0, bufferSize);
            _saltGenerator.Generate(buffer.Slice(_algorithmNameLength + 1));
            buffer[_algorithmNameLength] = 0x00;
            _algorithm.EncodedUtf8Bytes.CopyTo(buffer);

            Span <byte> derivedKey = stackalloc byte[KeySizeThreshold].Slice(0, _keySizeInBytes);

            Pbkdf2.DeriveKey(_password, buffer, _hashAlgorithm, _iterationCount, derivedKey);

            Span <byte> salt          = buffer.Slice(_algorithmNameLength + 1, _saltSizeInBytes);
            int         saltLengthB64 = Base64Url.GetArraySizeRequiredToEncode(salt.Length);

            byte[]? arrayToReturn = null;
            Span <byte> b64Salt = saltLengthB64 > Pbkdf2.SaltSizeThreshold * 4 / 3
                ? (arrayToReturn = ArrayPool <byte> .Shared.Rent(saltLengthB64))
                : stackalloc byte[Pbkdf2.SaltSizeThreshold * 4 / 3];

            try
            {
                int length = Base64Url.Encode(salt, b64Salt);
                header.Add(JwtHeaderParameterNames.P2s, Utf8.GetString(b64Salt.Slice(0, saltLengthB64)));
                header.Add(JwtHeaderParameterNames.P2c, _iterationCount);

                using var keyWrapper = new AesKeyWrapper(derivedKey, EncryptionAlgorithm, _keyManagementAlgorithm);
                return(keyWrapper.WrapKey(contentEncryptionKey, header, destination));
            }
            finally
            {
                if (bufferToReturn != null)
                {
                    ArrayPool <byte> .Shared.Return(bufferToReturn);
                }

                if (arrayToReturn != null)
                {
                    ArrayPool <byte> .Shared.Return(arrayToReturn);
                }
            }
        }
Пример #5
0
        private async Task <JwtHeader> BuildJwtHeader()
        {
            var header = new JwtHeader();

            var publicKey = await _digitalSigner.GetPublicKey();

            header.Add("x5c", new[] { publicKey });
            header.Add("alg", SecurityAlgorithms.RsaSha256);
            header.Add("typ", "JWT");

            return(header);
        }
Пример #6
0
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="keyVaultCredentials">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual Task <JwtHeader> CreateHeaderAsync(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials)
        {
            var header = new JwtHeader(keyVaultCredentials);

            if (keyVaultCredentials != null)
            {
                header.Add("kid", _options.KeyIdentifier);
                header.Add("x5t", _options.KeyIdentifier);
            }

            return(Task.FromResult(header));
        }
        private async Task <JwtHeader> BuildJwtHeader()
        {
            var header = new JwtHeader();

            header.Remove("alg");

            var keys = await GetCertificates();

            header.Add("x5c", keys);
            header.Add("alg", SecurityAlgorithms.RsaSha256);
            header.Add("typ", "JWT");

            return(header);
        }
Пример #8
0
        public string GetJWTToken(Device device)
        {
            if (JWTService.TokenKeysHolder.keys.Count == 0)
            {
                return(null);
            }
            string sec = JWTService.TokenKeysHolder.keys[0].k;

            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(sec));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
            var header             = new JwtHeader(signingCredentials);

            header.Add("kid", JWTService.TokenKeysHolder.keys[0].kid);
            var claims = new[]
            {
                new Claim("serialID", device.OriginalID.ToString()),
                new Claim("carID", device.CarID.ToString(), ClaimValueTypes.Integer64),
                new Claim("deviceID", device.ID.ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Exp, ((Int32)(DateTime.UtcNow.AddDays(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Aud, "https://auth.mgduke.com")
            };
            var payload     = new JwtPayload(claims);
            var secToken    = new JwtSecurityToken(header, payload);
            var handler     = new JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);


            return(tokenString);
        }
        private static JwtHeader ComposeHeader()
        {
            JwtHeader result = new JwtHeader();

            result.Add(EventToken.HeaderKeyAlgorithm, EventToken.JwtAlgorithmNone);
            return(result);
        }
Пример #10
0
        private string ConstructJWTAssertion(string sub, string boxSubType)
        {
            byte[] randomNumber = new byte[64];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(randomNumber);
            }

            var claims = new List <Claim> {
                new Claim("sub", sub),
                new Claim("box_sub_type", boxSubType),
                new Claim("jti", Convert.ToBase64String(randomNumber)),
            };

            var payload = new JwtPayload(this.boxConfig.ClientId, AUTH_URL, claims, null, DateTime.UtcNow.AddSeconds(30));

            var header = new JwtHeader(signingCredentials: this.credentials);

            if (this.boxConfig.JWTPublicKeyId != null)
            {
                header.Add("kid", this.boxConfig.JWTPublicKeyId);
            }

            var    token        = new JwtSecurityToken(header, payload);
            var    tokenHandler = new JwtSecurityTokenHandler();
            string assertion    = tokenHandler.WriteToken(token);

            return(assertion);
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns>The JWT header</returns>
        protected virtual async Task <JwtHeader> CreateHeaderAsync(Token token)
        {
            var credential = await Keys.GetSigningCredentialsAsync();

            if (credential == null)
            {
                throw new InvalidOperationException("No signing credential is configured. Can't create JWT token");
            }

            var header = new JwtHeader(credential);

            // emit x5t claim for backwards compatibility with v4 of MS JWT library
            if (credential.Key is X509SecurityKey x509key)
            {
                var cert = x509key.Certificate;
                if (IdentityServerDateTime.UtcNow > cert.NotAfter)
                {
                    Logger.LogWarning("Certificate {subjectName} has expired on {expiration}", cert.Subject, cert.NotAfter.ToString());
                }

                header.Add("x5t", Base64Url.Encode(cert.GetCertHash()));
            }

            return(header);
        }
        static string Authorization()
        {
            string apiKey    = Environment.GetEnvironmentVariable("ID4I_API_KEY");
            string apiSecret = Environment.GetEnvironmentVariable("ID4I_API_SECRET");

            if (apiKey == null || apiSecret == null)
            {
                Console.WriteLine("ID4I_API_KEY or ID4I_API_SECRET not set in environment");
                Environment.Exit(-1);
            }

            var secureKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(apiSecret));

            SigningCredentials credentials = new SigningCredentials
                                                 (secureKey, SecurityAlgorithms.HmacSha512); // SecurityAlgorithms.HmacSha512 = HS512 | SecurityAlgorithms.RsaSha256 = RS256

            var header = new JwtHeader(credentials);

            header.Remove("typ");
            header.Add("typ", "API"); // force typ to be "API"

            var payload = new JwtPayload
            {
                { "sub", apiKey },
                { "iat", DateTime.UtcNow },
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            var tokenString = handler.WriteToken(secToken);

            return(tokenString);
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual async Task<JwtHeader> CreateHeaderAsync(Token token, SecurityKey key)
        {
            JwtHeader header = null;

#if DOTNET5_4
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature));
#elif NET451
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

            var x509key = key as X509SecurityKey;
            if (x509key != null)
            {
                header.Add("kid", await _keyService.GetKidAsync(x509key.Certificate));
                header.Add("x5t", await _keyService.GetKidAsync(x509key.Certificate));
            }
#endif

            return header;
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual async Task <JwtHeader> CreateHeaderAsync(Token token, SecurityKey key)
        {
            JwtHeader header = null;

#if DOTNET5_4
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature));
#elif NET451
            header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest));

            var x509key = key as X509SecurityKey;
            if (x509key != null)
            {
                header.Add("kid", await _keyService.GetKidAsync(x509key.Certificate));
                header.Add("x5t", await _keyService.GetKidAsync(x509key.Certificate));
            }
#endif

            return(header);
        }
Пример #15
0
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="keyVaultCredentials">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual JwtHeader CreateHeader(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials)
        {
            var header = new JwtHeader(keyVaultCredentials);

            if (keyVaultCredentials != null)
            {
                header.Add("kid", _options.KeyIdentifier);
            }

            return(header);
        }
        private void AddHeaderParameters(JwtHeader header, JWTOptions options)
        {
            HeaderParameters            parameters = options.GetHeaderParameters();
            List <string>               list       = parameters.GetAll();
            Dictionary <string, object> map        = parameters.GetMap();

            foreach (string s in list)
            {
                header.Add(s.Trim(), ((string)map[s]).Trim());
            }
        }
Пример #17
0
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        private async Task <JwtHeader> CreateHeaderAsync(SigningCredentials credential)
        {
            var header = new JwtHeader(credential);

            var x509credential = credential as X509SigningCredentials;

            if (x509credential != null)
            {
                header.Add("kid", await _keyService.GetKidAsync(x509credential.Certificate));
            }

            return(header);
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        private async Task <JwtHeader> CreateHeaderAsync(SigningCredentials credential)
        {
            var header = new JwtHeader(credential);

            var x509credential = credential as X509SigningCredentials;

            if (x509credential != null)
            {
                header.Add("kid", (await _keyService.GetSigningKeyAsync()).Kid);
            }

            return(header);
        }
Пример #19
0
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual JwtHeader CreateHeader(Token token, SigningCredentials credential)
        {
            var header = new JwtHeader(credential);

            var x509credential = credential as X509SigningCredentials;

            if (x509credential != null)
            {
                header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash()));
            }

            return(header);
        }
Пример #20
0
        private static void UpdateJwtHeader(SecurityKey key, JwtHeader header)
        {
            if (key is X509SecurityKey x509Key)
            {
                var thumbprint = Base64Url.Encode(x509Key.Certificate.GetCertHash());
                var x5c        = GenerateX5c(x509Key.Certificate);
                var pubKey     = x509Key.PublicKey as RSA;

                if (pubKey == null)
                {
                    throw new UnsupportedSigningKeyTypeException("Only certificates based on RSA keys are supported at the moment");
                }

                var parameters = pubKey.ExportParameters(false);
                var exponent   = Base64Url.Encode(parameters.Exponent);
                var modulus    = Base64Url.Encode(parameters.Modulus);

                header.Add("x5c", x5c);
                header.Add("kty", pubKey.SignatureAlgorithm);
                header.Add("use", "sig");
                header.Add("x5t", thumbprint);
                header.Add("e", exponent);
                header.Add("n", modulus);
            }

            if (key is RsaSecurityKey rsaKey)
            {
                var parameters = rsaKey.Rsa?.ExportParameters(false) ?? rsaKey.Parameters;
                var exponent   = Base64Url.Encode(parameters.Exponent);
                var modulus    = Base64Url.Encode(parameters.Modulus);

                header.Add("kty", "RSA");
                header.Add("use", "sig");
                header.Add("e", exponent);
                header.Add("n", modulus);
            }
        }
Пример #21
0
        public void MatchX5t()
        {
            X509SecurityKey signingKey  = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256;
            X509SecurityKey validateKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256_Public;

            // Assume SigningKey.KeyId doesn't match validationParameters.IssuerSigningKey.KeyId
            signingKey.KeyId = null;
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256Signature);

            var header = new JwtHeader(signingCredentials);

            header.Add(JwtHeaderParameterNames.X5t, Base64UrlEncoder.Encode(KeyingMaterial.CertSelfSigned2048_SHA256.GetCertHash()));
            var payload = new JwtPayload();

            payload.AddClaims(ClaimSets.DefaultClaims);

            var jwtToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();
            var jwt      = handler.WriteToken(jwtToken);

            var validationParameters =
                new TokenValidationParameters
            {
                RequireExpirationTime = false,
                RequireSignedTokens   = true,
                ValidateAudience      = false,
                ValidateIssuer        = false,
                ValidateLifetime      = false,
            };

            validationParameters.IssuerSigningKey = validateKey;

            SecurityToken validatedSecurityToken = null;
            var           cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            validateKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA384_Public;
            validationParameters.IssuerSigningKey = validateKey;

            ExpectedException expectedException = ExpectedException.SecurityTokenInvalidSignatureException("IDX10503:");

            try
            {
                cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
Пример #22
0
        /// <summary>
        /// Create and sign JWT token.
        /// </summary>
        public static JwtSecurityToken CreateToken(SecurityKey securityKey, string issuer, IEnumerable <string> audiences, IEnumerable <Claim> claims, DateTimeOffset?issuedAt = null, int beforeIn = 60, int expiresIn = 3600, string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256, string x509CertificateSHA1Thumbprint = null)
        {
            if (securityKey == null)
            {
                new ArgumentNullException(nameof(securityKey));
            }
            if (issuer.IsNullOrEmpty())
            {
                new ArgumentNullException(nameof(issuer));
            }
            if (audiences?.Count() < 1)
            {
                throw new ArgumentException($"At least one audience is required.", nameof(audiences));
            }
            if (claims?.Count() < 1)
            {
                throw new ArgumentException($"At least one claim is required.", nameof(claims));
            }

            var header = new JwtHeader(new SigningCredentials(securityKey, algorithm));

            x509CertificateSHA1Thumbprint = x509CertificateSHA1Thumbprint ?? GetX509CertificateSHA1Thumbprint(securityKey);
            if (!x509CertificateSHA1Thumbprint.IsNullOrEmpty())
            {
                header.Add(IdentityConstants.JwtHeaders.X509CertificateSHA1Thumbprint, x509CertificateSHA1Thumbprint);
            }

            if (!issuedAt.HasValue)
            {
                issuedAt = DateTimeOffset.UtcNow;
            }
            var payload = new JwtPayload(issuer, audiences.First(), claims, issuedAt.Value.AddSeconds(-beforeIn).UtcDateTime, issuedAt.Value.AddSeconds(expiresIn).UtcDateTime, issuedAt.Value.UtcDateTime);

            if (audiences.Count() > 1)
            {
                foreach (var audience in audiences.Skip(1))
                {
                    payload.AddClaim(new Claim(JwtClaimTypes.Audience, audience));
                }
            }
            return(new JwtSecurityToken(header, payload));
        }
Пример #23
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            Debug.Assert(header != null);

            var partyUInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apu);
            var partyVInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apv);
            var secretAppend = BuildSecretAppend(partyUInfo, partyVInfo);
            ReadOnlySpan <byte> exchangeHash;
            var             ecKey         = _key;
            var             otherPartyKey = ecKey.CreateEcdhKey();
            ECDiffieHellman ephemeralKey  = (staticKey is null) ? ECDiffieHellman.Create(ecKey.Crv.CurveParameters) : ((ECJwk)staticKey).CreateEcdhKey();

            try
            {
                exchangeHash = new ReadOnlySpan <byte>(ephemeralKey.DeriveKeyFromHash(otherPartyKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes);
                var epk = ECJwk.FromParameters(ephemeralKey.ExportParameters(false));
                header.Add(JwtHeaderParameterNames.Epk, epk);
            }
            finally
            {
                if (staticKey is null)
                {
                    ephemeralKey.Dispose();
                }
            }

            SymmetricJwk contentEncryptionKey;

            if (Algorithm.ProduceEncryptionKey)
            {
                using var keyWrapper = new AesKeyWrapper(exchangeHash, EncryptionAlgorithm, _keyManagementAlgorithm !);
                contentEncryptionKey = keyWrapper.WrapKey(null, header, destination);
            }
            else
            {
                exchangeHash.CopyTo(destination);
                contentEncryptionKey = SymmetricJwk.FromSpan(exchangeHash, false);
            }

            return(contentEncryptionKey);
        }
Пример #24
0
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual async Task <JwtHeader> CreateHeaderAsync(Token token)
        {
            var credential = await _keys.GetSigningCredentialsAsync();

            if (credential == null)
            {
                throw new InvalidOperationException("No signing credential is configured. Can't create JWT token");
            }

            var header = new JwtHeader(credential);

            // emit x5t claim for backwards compatibility with v4 of MS JWT library
            var x509key = credential.Key as X509SecurityKey;

            if (x509key != null)
            {
                header.Add("x5t", Base64Url.Encode(x509key.Certificate.GetCertHash()));
            }

            return(header);
        }
Пример #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseAuthentication();

            //Get JWT secret key and id from config
            var jwtSecretKey = Configuration["JwtSecret:SecretKey:k"];
            var jwtSecretId  = Configuration["JwtSecret:SecretKey:kid"];

            //Convert secretKey from base 64
            var jwtSecretKeyFromBase64 = new SymmetricSecurityKey(Convert.FromBase64String(jwtSecretKey));
            var signingCredentials     = new SigningCredentials(jwtSecretKeyFromBase64, SecurityAlgorithms.HmacSha256);

            var header = new JwtHeader(signingCredentials);

            header.Add("kid", jwtSecretId);

            var options = new TokenProviderOptions
            {
                Header = header
            };

            app.UseMiddleware <ResetPasswordProviderMiddleware>();
            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));
            app.UseMiddleware <RegisterProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public string GenerateJWT()
        {
            DateTime UnixEpoch           = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            // Provide proper private key
            string privateSecretKey = "OfED+KgbZxtu4e4+JSQWdtSgTnuNixKy1nMVAEww8QL3IN33XusJhrz9HXmIrdyX2F41xJHG4uj5/2Dzv3xjYYvqxexm3X3X5TOf3WoM1VNloJ7UnbqUJOiEjgK8sRdJntgfomO4U8s67cpysk0h9rc0He4xRspEjOapFfDg+VG8igidcNgbNDSSaV4491Fo3sq2aGSCtYvekzs7JwXJnNAyvDSJjfK/7M8MpxSMnm1vMscBXyiYFXhGC4wqWlYBE828/5DNyw3QZW5EjD7hvDrY5OlYd4smCTa53helNnJz5NT9HQaDbE2sMwIDAQABAoIBAEs63TvT94njrPDP3A/sfCEXg1F2y0D/PjzUhM1aJGcRiOUXnGlYdViGhLnnJoNZTZm9qI1LT0NWcDA5NmBN6gcrk2EApyTt1D1i4AQ66rYoTF9iEC4Wye28v245BYESA6IIelgIxXGsVyllERsbTkaphzibbYfHmvwMxkn135Zfzd/NOXl/O32vYIomzrNEP+tN2WXhhG8c8+iZ8PErBV3CqrYogYy97d2CeQbXcpd5unPiU4TK0nnzeBAXdgeYuJHFC45YHl9UvShRoe6CHR47ceIGp6WMc5BTyyTkZpctuYJTwaChdj/QuRSkTYmn6jFL+MRfYQJ8VVwSVo5DbkECgYEA4/YIMKcwObYcSuHzgkMwH645CRDoy9M98eptAoNLdJBHYz23U5IbGL1+qHDDCPXxKs9ZG7EEqyWezq42eoFoebLA5O6/xrYXoaeIb094dbCF4D932hAkgAaAZkZVsSiWDCjYSV+JoWX4NVBcIL9yyHRhaaPVULTRbPsZQWq9+hMCgYEA48j4RGO7CaVpgUVobYasJnkGSdhkSCd1VwgvHH3vtuk7/JGUBRaZc0WZGcXkAJXnLh7QnDHOzWASdaxVgnuviaDi4CIkmTCfRqPesgDR2Iu35iQsH7P2/o1pzhpXQS/Ct6J7/GwJTqcXCvp4tfZDbFxS8oewzp4RstILj+pDyWECgYByQAbOy5xB8GGxrhjrOl1OI3V2c8EZFqA/NKy5y6/vlbgRpwbQnbNy7NYj+Y/mV80tFYqldEzQsiQrlei78Uu5YruGgZogL3ccj+izUPMgmP4f6+9XnSuN9rQ3jhy4k4zQP1BXRcim2YJSxhnGV+1hReLknTX2IwmrQxXfUW4xfQKBgAHZW8qSVK5bXWPjQFnDQhp92QM4cnfzegxe0KMWkp+VfRsrw1vXNx";

            rsa = DecodeRSAPrivateKey(FromBase64Url(privateSecretKey));
            //convert to csp format
            var bytes     = rsa.ExportCspBlob(false);
            var publicKey = Convert.ToBase64String(bytes);
            //
            RsaSecurityKey _signingKey = new RsaSecurityKey(rsa);

            Microsoft.IdentityModel.Tokens.SigningCredentials signingCredentials =
                new Microsoft.IdentityModel.Tokens.SigningCredentials(_signingKey, SecurityAlgorithms.RsaSha256);
            JwtHeader head = new JwtHeader(signingCredentials);

            head.Add("kid", "lzo-firstpublickey");

            string sNewGuid = Guid.NewGuid().ToString("n");
            var    claims   = new[]
            {
                new Claim(JwtRegisteredClaimNames.Iss, "s6BhdRkqt3"),
                new Claim(JwtRegisteredClaimNames.Sub, "s6BhdRkqt3"),
                new Claim(JwtRegisteredClaimNames.Aud, "https://cis.ncrs/connect/token"),
                new Claim(JwtRegisteredClaimNames.Jti, sNewGuid),
                new Claim(JwtRegisteredClaimNames.Exp, ((Int64)DateTime.Now.AddMinutes(55).Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Iat, ((Int64)DateTime.Now.Subtract(UnixEpoch).TotalSeconds).ToString(System.Globalization.CultureInfo.InvariantCulture), ClaimValueTypes.Integer64)
            };
            JwtPayload       payload = new JwtPayload(claims);
            JwtSecurityToken jwt     = new JwtSecurityToken(head, payload);

            jwt.SigningKey = _signingKey;
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
Пример #27
0
        private string ConstructJWTAssertion(string sub, string boxSubType, DateTimeOffset?nowOverride = null)
        {
            var randomNumber = new byte[64];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
            }

            var claims = new List <Claim> {
                new Claim("sub", sub),
                new Claim("box_sub_type", boxSubType),
                new Claim("jti", Convert.ToBase64String(randomNumber)),
            };

            DateTimeOffset expireTime = DateTimeOffset.UtcNow.AddSeconds(30);

            if (nowOverride.HasValue)
            {
                expireTime = nowOverride.Value.AddSeconds(30);
            }

            var payload = new JwtPayload(_boxConfig.ClientId, new Uri(_boxConfig.BoxApiHostUri, Constants.AuthTokenEndpointString).ToString(),
                                         claims, null, expireTime.LocalDateTime);

            var header = new JwtHeader(signingCredentials: _credentials);

            if (_boxConfig.JWTPublicKeyId != null)
            {
                header.Add("kid", _boxConfig.JWTPublicKeyId);
            }

            var token        = new JwtSecurityToken(header, payload);
            var tokenHandler = new JwtSecurityTokenHandler();
            var assertion    = tokenHandler.WriteToken(token);

            return(assertion);
        }
        /// <summary>
        /// Create JWT
        /// Refer to https://www.developer.saxo/openapi/learn/oauth-certificate-based-authentication
        /// </summary>
        /// <param name="spUrl"></param>
        /// <param name="userId"></param>
        /// <param name="appKey"></param>
        /// <param name="idpUrl"></param>
        /// <param name="signCert"></param>
        /// <returns></returns>
        private string CreateAssertion(App app, Certificate certificate)
        {
            var issuer   = app.AppKey;
            var audience = app.AuthorizationEndpoint;
            var appUrl   = app.ServiceProviderUrl;

            var claims = new List <Claim>();

            claims.Add(new Claim("spurl", appUrl));
            claims.Add(new Claim("sub", certificate.UserId));
            claims.Add(new Claim("iss", issuer));
            claims.Add(new Claim("aud", audience));
            claims.Add(new Claim("exp", (DateTime.UtcNow.AddHours(5) - new DateTime(1970, 1, 1)).TotalSeconds.ToString()));

            var key    = new X509SecurityKey(certificate.ClientCertificate);
            var header = new JwtHeader(new SigningCredentials(key, SecurityAlgorithms.RsaSha256));

            header.Add("x5t", certificate.ClientCertificate.Thumbprint);

            var jsonWebToken = new JwtSecurityToken(header, new JwtPayload(issuer, audience, claims, null, null));

            return(new JwtSecurityTokenHandler().WriteToken(jsonWebToken));
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual JwtHeader CreateHeader(Token token, SigningCredentials credential)
        {
            var header = new JwtHeader(credential);

            var x509credential = credential as X509SigningCredentials;
            if (x509credential != null)
            {
                header.Add("kid", Base64Url.Encode(x509credential.Certificate.GetCertHash()));
            }

            return header;
        }
Пример #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
                {
                    HotModuleReplacement      = true,
                    ReactHotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseAuthentication();

            //Get JWT secret key and id from config
            var jwtSecretKey = Configuration["JwtSecret:SecretKey:k"];
            var jwtSecretId  = Configuration["JwtSecret:SecretKey:kid"];

            //Convert secretKey from base 64
            var jwtSecretKeyFromBase64 = new SymmetricSecurityKey(Convert.FromBase64String(jwtSecretKey));
            var signingCredentials     = new SigningCredentials(jwtSecretKeyFromBase64, SecurityAlgorithms.HmacSha256);

            var header = new JwtHeader(signingCredentials);

            header.Add("kid", jwtSecretId);

            var options = new TokenProviderOptions
            {
                Header = header
            };

            app.UseMiddleware <ResetPasswordProviderMiddleware>();
            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));
            app.UseMiddleware <RegisterProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
        }
Пример #31
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

#if DEBUG
            //app.UseCors(builder =>
            //    builder.WithOrigins("http://localhost:8080"));
            app.UseCors("CorsPolicy");
#endif

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme  = "ApplicationCookie",
                AutomaticAuthenticate = true
            });

            app.UseFacebookAuthentication(new FacebookOptions
            {
                AppId     = Configuration["FacebookOptions:AppId"],
                AppSecret = Configuration["FacebookOptions:AppSecret"]
            });

            app.UseGoogleAuthentication(new GoogleOptions()
            {
                ClientId     = Configuration["GoogleOptions:ClientId"],
                ClientSecret = Configuration["GoogleOptions:ClientSecret"]
            });

            app.UseApplicationInsightsRequestTelemetry();

            app.UseApplicationInsightsExceptionTelemetry();

            //Get JWT secret key and id from config
            var jwtSecretKey = Configuration["JwtSecret:SecretKey:k"];
            var jwtSecretId  = Configuration["JwtSecret:SecretKey:kid"];

            //Convert secretKey from base 64
            var jwtSecretKeyFromBase64 = new SymmetricSecurityKey(Convert.FromBase64String(jwtSecretKey));
            var signingCredentials     = new SigningCredentials(jwtSecretKeyFromBase64, SecurityAlgorithms.HmacSha256);

            var header = new JwtHeader(signingCredentials);
            header.Add("kid", jwtSecretId);

            var options = new TokenProviderOptions
            {
                Header = header
            };

            app.UseMiddleware <ResetPasswordProviderMiddleware>();
            app.UseMiddleware <TokenProviderMiddleware>(Options.Create(options));
            app.UseMiddleware <RegisterProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        public void CreateAndValidateTokens_MultipleX5C()
        {
            List <string> errors  = new List <string>();
            var           handler = new JwtSecurityTokenHandler();
            var           payload = new JwtPayload();
            var           header  = new JwtHeader();

            payload.AddClaims(ClaimSets.MultipleAudiences(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer));
            List <string> x5cs = new List <string> {
                "x5c1", "x5c2"
            };

            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            var jwtToken = new JwtSecurityToken(header, payload);
            var jwt      = handler.WriteToken(jwtToken);

            var validationParameters =
                new TokenValidationParameters
            {
                RequireExpirationTime = false,
                RequireSignedTokens   = false,
                ValidateAudience      = false,
                ValidateIssuer        = false,
                ValidateLifetime      = false,
            };

            SecurityToken validatedSecurityToken = null;
            var           cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            JwtSecurityToken validatedJwt = validatedSecurityToken as JwtSecurityToken;
            object           x5csInHeader = validatedJwt.Header[JwtHeaderParameterNames.X5c];

            if (x5csInHeader == null)
            {
                errors.Add("1: validatedJwt.Header[JwtHeaderParameterNames.X5c]");
            }
            else
            {
                var list = x5csInHeader as IEnumerable <object>;
                if (list == null)
                {
                    errors.Add("2: var list = x5csInHeader as IEnumerable<object>; is NULL.");
                }

                int num = 0;
                foreach (var str in list)
                {
                    num++;
                    if (!(str is string))
                    {
                        errors.Add("3: str is not string, is:" + str.ToString());
                    }
                }

                if (num != x5cs.Count)
                {
                    errors.Add("4: num != x5cs.Count. num: " + num.ToString() + "x5cs.Count: " + x5cs.Count.ToString());
                }
            }

            // make sure we can still validate with existing logic.
            header = new JwtHeader(KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2);
            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            jwtToken = new JwtSecurityToken(header, payload);
            jwt      = handler.WriteToken(jwtToken);

            validationParameters.IssuerSigningToken  = KeyingMaterial.DefaultAsymmetricX509Token_2048;
            validationParameters.RequireSignedTokens = true;
            validatedSecurityToken = null;
            cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors);
        }
Пример #33
0
        public void MultipleX5C()
        {
            List <string> errors  = new List <string>();
            var           handler = new JwtSecurityTokenHandler();
            var           payload = new JwtPayload();
            var           header  = new JwtHeader();

            payload.AddClaims(ClaimSets.DefaultClaims);
            List <string> x5cs = new List <string> {
                "x5c1", "x5c2"
            };

            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            var jwtToken = new JwtSecurityToken(header, payload);
            var jwt      = handler.WriteToken(jwtToken);

            var validationParameters =
                new TokenValidationParameters
            {
                RequireExpirationTime = false,
                RequireSignedTokens   = false,
                ValidateAudience      = false,
                ValidateIssuer        = false,
                ValidateLifetime      = false,
            };

            SecurityToken validatedSecurityToken = null;
            var           cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            JwtSecurityToken validatedJwt = validatedSecurityToken as JwtSecurityToken;
            object           x5csInHeader = validatedJwt.Header[JwtHeaderParameterNames.X5c];

            if (x5csInHeader == null)
            {
                errors.Add("1: validatedJwt.Header[JwtHeaderParameterNames.X5c]");
            }
            else
            {
                var list = x5csInHeader as IEnumerable <object>;
                if (list == null)
                {
                    errors.Add("2: var list = x5csInHeader as IEnumerable<object>; is NULL.");
                }

                int num = 0;
                foreach (var str in list)
                {
                    var value = str as Newtonsoft.Json.Linq.JValue;
                    if (value != null)
                    {
                        string aud = value.Value as string;
                        if (aud != null)
                        {
                        }
                    }
                    else if (!(str is string))
                    {
                        errors.Add("3: str is not string, is: " + str.GetType());
                        errors.Add("token : " + validatedJwt.ToString());
                    }
                    num++;
                }

                if (num != x5cs.Count)
                {
                    errors.Add("4: num != x5cs.Count. num: " + num.ToString() + "x5cs.Count: " + x5cs.Count.ToString());
                }
            }

            X509SecurityKey signingKey  = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256;
            X509SecurityKey validateKey = KeyingMaterial.X509SecurityKeySelfSigned2048_SHA256_Public;

            // make sure we can still validate with existing logic.
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256Signature);

            header = new JwtHeader(signingCredentials);
            header.Add(JwtHeaderParameterNames.X5c, x5cs);
            jwtToken = new JwtSecurityToken(header, payload);
            jwt      = handler.WriteToken(jwtToken);

            validationParameters.IssuerSigningKey    = validateKey;
            validationParameters.RequireSignedTokens = true;
            validatedSecurityToken = null;
            cp = handler.ValidateToken(jwt, validationParameters, out validatedSecurityToken);

            TestUtilities.AssertFailIfErrors("CreateAndValidateTokens_MultipleX5C", errors);
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="keyVaultCredentials">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual JwtHeader CreateHeader(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials)
        {
            var header = new JwtHeader(keyVaultCredentials);
            if (keyVaultCredentials != null)
            {
                header.Add("kid", _options.KeyIdentifier);
            }

            return header;
        }
Пример #35
0
        private string ConstructJWTAssertion(string sub, string boxSubType)
        {
            byte[] randomNumber = new byte[64];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(randomNumber);
            }

            var claims = new List<Claim>{
                new Claim("sub", sub),
                new Claim("box_sub_type", boxSubType),
                new Claim("jti", Convert.ToBase64String(randomNumber)),
            };

            var payload = new JwtPayload(this.boxConfig.ClientId, AUTH_URL, claims, null, DateTime.UtcNow.AddSeconds(30));

            var header = new JwtHeader(signingCredentials: this.credentials);
            if (this.boxConfig.JWTPublicKeyId != null)
                header.Add("kid", this.boxConfig.JWTPublicKeyId);

            var token = new JwtSecurityToken(header, payload);
            var tokenHandler = new JwtSecurityTokenHandler();
            string assertion = tokenHandler.WriteToken(token);
            return assertion;
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="credential">The credentials.</param>
        /// <returns>The JWT header</returns>
        private async Task<JwtHeader> CreateHeaderAsync(SigningCredentials credential)
        {
            var header = new JwtHeader(credential);

            var x509credential = credential as X509SigningCredentials;
            if (x509credential != null)
            {
                header.Add("kid", await _keyService.GetKidAsync(x509credential.Certificate));
            }

            return header;
        }
        /// <summary>
        /// Creates the JWT header
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="keyVaultCredentials">The credentials.</param>
        /// <returns>The JWT header</returns>
        protected virtual Task<JwtHeader> CreateHeaderAsync(Token token, AzureKeyVaultSigningCredentials keyVaultCredentials)
        {
            var header = new JwtHeader(keyVaultCredentials);
            if (keyVaultCredentials != null)
            {
                header.Add("kid", _options.KeyIdentifier);
                header.Add("x5t", _options.KeyIdentifier);
            }

            return Task.FromResult(header);
        }