Ejemplo n.º 1
0
        /// <summary>
        /// Encodes given json string to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">json string to encode (not null or whitespace)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string Encode(string payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[] headerBytes  = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));
            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payloadBytes));

            byte[] signature = HashAlgorithms[algorithm].Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payloadBytes, signature));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[] headerBytes = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            byte[] signature = HashAlgorithms[algorithm].Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Ejemplo n.º 3
0
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }
            if (extraHeaders == null)
            {
                extraHeaders = new Dictionary <string, object>()
                {
                    { "typ", "JWT" }
                };
            }
            Dictionary <string, object> strs = new Dictionary <string, object>()
            {
                { "alg", JWT.JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append <string, object>(strs, extraHeaders);
            byte[] bytes    = Encoding.UTF8.GetBytes(JWT.jsMapper.Serialize(strs));
            byte[] numArray = Encoding.UTF8.GetBytes(Compact.Serialize(new byte[][] { bytes, payload }));
            //SHA256 sha = SHA256.Create();
            //byte[] numArray1 = sha.ComputeHash(numArray);
            byte[] numArray1 = JWT.HashAlgorithms[algorithm].Sign(numArray, key);
            return(Compact.Serialize(new byte[][] { bytes, payload, numArray1 }));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }
            var jwtSettings = GetSettings(settings);

            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Ejemplo n.º 5
0
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }
            if (extraHeaders == null)
            {
                extraHeaders = new Dictionary <string, object>()
                {
                    { "typ", "JWT" }
                };
            }
            Dictionary <string, object> strs = new Dictionary <string, object>()
            {
                { "alg", JWT.JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append <string, object>(strs, extraHeaders);
            byte[] bytes    = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(strs));
            byte[] numArray = Encoding.UTF8.GetBytes(Compact.Serialize(new byte[][] { bytes, payload }));
            //byte[] numArray1 = JWT.HashAlgorithms[algorithm].Sign(numArray, key);
            SHA512 sha1 = SHA512.Create();

            byte[] numArray1 = sha1.ComputeHash(numArray);
            //System.Security.Cryptography.SHA512Cng  --
            return(Compact.Serialize(new byte[][] { bytes, payload, numArray1 }));
        }
        public void ShouldGetCurrentToSignAndValidateJws(string algorithm, KeyType keyType)
        {
            var options = new JwksOptions()
            {
                Jws = JwsAlgorithm.Create(algorithm, keyType), KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_"
            };

            _jwksService.GenerateSigningCredentials(options);
            var signingCredentials = _jwksService.GetCurrentSigningCredentials();
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt    = handler.CreateToken(descriptor);
            var result = handler.ValidateToken(jwt,
                                               new TokenValidationParameters
            {
                ValidIssuer      = "me",
                ValidAudience    = "you",
                IssuerSigningKey = signingCredentials.Key
            });

            result.IsValid.Should().BeTrue();
        }
        public ISignatureValidator Create(TokenHeader header, JwsAlgorithm algorithm)
        {
            switch (algorithm)
            {
            case JwsAlgorithm.RS256:
            case JwsAlgorithm.RS384:
            case JwsAlgorithm.RS512:
                return(new Rsa(header, algorithm, GetLogger <Rsa>()));

            case JwsAlgorithm.HS256:
            case JwsAlgorithm.HS384:
            case JwsAlgorithm.HS512:
                return(new Hmac(header, algorithm, GetLogger <Hmac>()));

            case JwsAlgorithm.ES256:
            case JwsAlgorithm.ES384:
            case JwsAlgorithm.ES512:
                return(new Ecdsa(header, algorithm, GetLogger <Ecdsa>()));

            case JwsAlgorithm.PS256:
            case JwsAlgorithm.PS384:
            case JwsAlgorithm.PS512:
                throw Logger.Exception($"The JWS signature algorithm {algorithm} is not supported yet");

            default:
                throw Logger.Exception("Invalid JWS Algorithm");
            }
        }
Ejemplo n.º 8
0
 public void ShouldGenerate(string algorithm, KeyType keyType)
 {
     _keyService.GenerateSigningCredentials(new JwksOptions()
     {
         KeyPrefix = "ShouldGenerateManyRsa_", Jws = JwsAlgorithm.Create(algorithm, keyType)
     });
 }
Ejemplo n.º 9
0
        public void ShouldKeepPublicKeyAfterUpdateAExpiredJwk(string algorithm, KeyType keyType)
        {
            var alg = JwsAlgorithm.Create(algorithm, keyType);
            var key = _keyService.GenerateSigningCredentials(new JwksOptions()
            {
                KeyPrefix = "ShouldGenerateManyRsa_", Jws = alg
            });
            var privateKey = new SecurityKeyWithPrivate();

            privateKey.SetJwsParameters(key.Key, alg);
            _jsonWebKeyStore.Save(privateKey);
            /*Remove private*/
            _jsonWebKeyStore.Revoke(privateKey);

            var jsonWebKey = _keyService.GetLastKeysCredentials(JsonWebKeyType.Jws, 5).First(w => w.Kid == privateKey.KeyId);

            jsonWebKey.Kty.Should().NotBeNullOrEmpty();
            jsonWebKey.HasPrivateKey.Should().BeFalse();
            switch (jsonWebKey.Kty)
            {
            case JsonWebAlgorithmsKeyTypes.EllipticCurve:
                jsonWebKey.X.Should().NotBeNullOrEmpty();
                jsonWebKey.Y.Should().NotBeNullOrEmpty();
                break;

            case JsonWebAlgorithmsKeyTypes.RSA:
                jsonWebKey.N.Should().NotBeNullOrEmpty();
                jsonWebKey.E.Should().NotBeNullOrEmpty();
                break;

            case JsonWebAlgorithmsKeyTypes.Octet:
                jsonWebKey.K.Should().NotBeNullOrEmpty();
                break;
            }
        }
Ejemplo n.º 10
0
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null)             //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", algorithm.ToString() }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Serialize(headerBytes, payload));

            var signer = SignerUtilities.GetSigner("SHA-384withECDSA");

            signer.Init(true, (ECPrivateKeyParameters)key);

            signer.BlockUpdate(bytesToSign, 0, bytesToSign.Length);
            byte[] signature = signer.GenerateSignature();

            return(Serialize(headerBytes, payload, transcodeSignatureToConcat(signature, 96)));
        }
Ejemplo n.º 11
0
        public static byte[] DecodeBytes(string token, object key, JwsAlgorithm alg)
        {
            JweAlgorithm? nullable  = null;
            JweEncryption?nullable1 = null;

            return(JWT.DecodeBytes(token, key, new JwsAlgorithm?(alg), nullable, nullable1));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Encodes given json string to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">json string to encode (not null or whitespace)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string Encode(string payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            return(EncodeBytes(payloadBytes, key, algorithm, extraHeaders, settings));
        }
Ejemplo n.º 13
0
 public JsonWebToken(string secret, JwsAlgorithm algorithm)
 {
     if (algorithm == JwsAlgorithm.HS256 || algorithm == JwsAlgorithm.HS384 || algorithm == JwsAlgorithm.HS512)
     {
         this.secret    = secret;
         this.algorithm = algorithm;
     }
     else
     {
         throw new Exception("Only HS256, HS384, and HS512 hashing algorithms are allowed");
     }
 }
Ejemplo n.º 14
0
        public void ShouldSaveCryptoAndRecover(string algorithm, KeyType keyType)
        {
            var options = new JwksOptions()
            {
                Jws = JwsAlgorithm.Create(algorithm, keyType)
            };
            var newKey = _keyService.GetCurrentSigningCredentials(options);

            _keyService.GetLastKeysCredentials(JsonWebKeyType.Jws, 5).Count.Should().BePositive();

            var currentKey = _keyService.GetCurrentSigningCredentials(options);

            newKey.Kid.Should().Be(currentKey.Kid);
        }
Ejemplo n.º 15
0
        public void PassCorrectToken(JwsAlgorithm algorithm, string key)
        {
            IdentityModelEventSource.ShowPII = true;

            var payload = GetPayload();
            var signKey = GetKey(key, algorithm);

            var token = JWT.Encode(payload, signKey, algorithm);

            var settings = BuildDefaultTokenValidationSettings();

            var validationParameters = settings.BuildTokenValidationParameters();
            var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out _);
            Assert.NotNull(claims);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <param name="options">additional encoding options</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null, JwtOptions options = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var jwtSettings = GetSettings(settings);
            var jwtOptions  = options ?? JwtOptions.Default;

            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }


            if (!jwtOptions.EncodePayload)
            {
                jwtHeader["b64"]  = false;
                jwtHeader["crit"] = Collections.Union(new[] { "b64" }, Dictionaries.Get <object>(extraHeaders, "crit"));
            }

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(securedInput(headerBytes, payload, jwtOptions.EncodePayload), key);


            byte[] payloadBytes = jwtOptions.DetachPayload ? new byte[0] : payload;


            return(jwtOptions.EncodePayload
                ? Compact.Serialize(headerBytes, payloadBytes, signature)
                : Compact.Serialize(headerBytes, Encoding.UTF8.GetString(payloadBytes), signature));
        }
Ejemplo n.º 17
0
        public void ShouldRemovePrivateAndUpdate(string algorithm, KeyType keyType)
        {
            var alg = JwsAlgorithm.Create(algorithm, keyType);
            var key = _keyService.GenerateSigningCredentials(new JwksOptions()
            {
                KeyPrefix = "ShouldGenerateManyRsa_", Jws = alg
            });
            var privateKey = new SecurityKeyWithPrivate();

            privateKey.SetJwsParameters(key.Key, alg);
            _jsonWebKeyStore.Save(privateKey);

            /*Remove private*/
            privateKey.Revoke();
            _jsonWebKeyStore.Revoke(privateKey);
        }
Ejemplo n.º 18
0
        public void WrongSignatureToken_Should_Fail(JwsAlgorithm algorithm, string key)
        {
            var payload = GetPayload();
            var signKey = GetKey(key, algorithm);

            var token = JWT.Encode(payload, signKey, algorithm);

            var settings = BuildDefaultTokenValidationSettings();

            var validationParameters = settings.BuildTokenValidationParameters();

            Assert.Throws<SecurityTokenInvalidSignatureException>(() =>
            {
                var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out SecurityToken securityToken);
            });
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Encodes given json string to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">json string to encode (not null or whitespace)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string Encode(string payload, object key, JwsAlgorithm algorithm)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

            var jwtHeader = new Dictionary <string, object> {
                { "typ", "JWT" }, { "alg", JwsAlgorithms[algorithm] }
            };

            byte[] headerBytes  = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));
            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payloadBytes));

            byte[] signature = HashAlgorithms[algorithm].Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payloadBytes, signature));
        }
Ejemplo n.º 20
0
        public void ShouldSaveDeterministicJwkRecoverAndSigning(string algorithm, KeyType keyType)
        {
            this.WarmupData.Clear();
            var options = new JwksOptions()
            {
                Jws = JwsAlgorithm.Create(algorithm, keyType)
            };

            var handler = new JsonWebTokenHandler();
            var now     = DateTime.Now;

            // Generate right now and in memory
            var newKey = _keyService.GetCurrentSigningCredentials(options);

            // recovered from database
            var currentKey = _keyService.GetCurrentSigningCredentials(options);

            newKey.Kid.Should().Be(currentKey.Kid);
            var claims     = new ClaimsIdentity(GenerateClaim().Generate(5));
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = claims,
                SigningCredentials = newKey
            };
            var descriptorFromDb = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = claims,
                SigningCredentials = currentKey
            };

            var jwt1 = handler.CreateToken(descriptor);
            var jwt2 = handler.CreateToken(descriptorFromDb);

            jwt1.Should().Be(jwt2);
        }
Ejemplo n.º 21
0
        public void WrongType_Should_Fail(JwsAlgorithm algorithm, string key)
        {
            var payload = GetPayload();
            payload = payload.Replace("access_token", "another");

            var signKey = GetKey(key, algorithm);

            var token = JWT.Encode(payload, signKey, algorithm);

            var settings = BuildDefaultTokenValidationSettings();

            var validationParameters = settings.BuildTokenValidationParameters();

            Assert.Throws<UnauthorizedAccessException>(() =>
            {
                var claims = new JwtSecurityTokenHandler().ValidateToken(token, validationParameters, out SecurityToken securityToken);
            });
        }
Ejemplo n.º 22
0
        private static object GetKey(string key, JwsAlgorithm algorithm)
        {
            switch (algorithm)
            {
                case JwsAlgorithm.HS256:
                    return Convert.FromBase64String(key);

                case JwsAlgorithm.RS256:
                    var rsa = new RSACryptoServiceProvider(2048);
                    var raw = Convert.FromBase64String(key);
                    var privateKey = Encoding.UTF8.GetString(raw);
                    rsa.FromXmlString(privateKey);
                    return rsa;

                default:
                    return null;
            }
        }
Ejemplo n.º 23
0
        public void ShouldNotBeSameJwtWhenProbabilisticToken(string algorithm, KeyType keyType)
        {
            var signingCredentials = _service.GenerateSigningCredentials(JwsAlgorithm.Create(algorithm, keyType));
            var handler            = new JsonWebTokenHandler();
            var now        = DateTime.Now;
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer             = "me",
                Audience           = "you",
                IssuedAt           = now,
                NotBefore          = now,
                Expires            = now.AddMinutes(5),
                Subject            = new ClaimsIdentity(GenerateClaim().Generate(5)),
                SigningCredentials = signingCredentials
            };

            var jwt1 = handler.CreateToken(descriptor);
            var jwt2 = handler.CreateToken(descriptor);

            jwt1.Should().NotBe(jwt2);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
                // nameof is not defined prior to c# 6.0 spec
                // throw new ArgumentNullException(nameof(payload));
                throw new ArgumentNullException("payload is null");
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }
            var jwtSettings = GetSettings(settings);


            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Ejemplo n.º 25
0
 public bool ValidateToken(string token, string secretKey, JwsAlgorithm jwsAlgorithm = JwsAlgorithm.HS256)
 {
     try
     {
         var secret  = Encoding.UTF8.GetBytes(secretKey);
         var payload = Jose.JWT.Decode <IDictionary <string, object> >(token, secret, jwsAlgorithm);
         var exp     = Convert.ToDateTime(payload["exp"]);
         if (exp < DateTime.Now)
         {
             throw new AuthException("登录超时,请重新登录");
         }
         return(true);
     }
     catch (Exception ex)
     {
         if (_logger.IsEnabled(LogLevel.Warning))
         {
             _logger.LogWarning("token验证失败,原因:" + ex.Message, ex);
         }
         return(false);
     }
 }
Ejemplo n.º 26
0
        public byte[] Sign(string keyId, byte[] payload, JwsAlgorithm algorithm)
        {
            HashAlgorithmName   hashAlgorithm;
            RSASignaturePadding padding;

            switch (algorithm)
            {
            case JwsAlgorithm.Rs256:
                hashAlgorithm = HashAlgorithmName.SHA256;
                padding       = RSASignaturePadding.Pkcs1;
                break;

            case JwsAlgorithm.Ps256:
                hashAlgorithm = HashAlgorithmName.SHA256;
                padding       = RSASignaturePadding.Pss;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null);
            }

            return(_keys[keyId].SignHash(payload, hashAlgorithm, padding));
        }
Ejemplo n.º 27
0
        //protected Dictionary<string, object> JoseDotNetCore(string token, JweEncryption enc, JweAlgorithm alg, byte[] key)
        //{
        //    return Jose.JWT.Decode<Dictionary<string, object>>(token, key: key, enc: enc/*JweEncryption.A128CBC_HS256*/, alg: alg/*JweAlgorithm.A128KW*/);
        //}

        protected Dictionary <string, object> JoseDotNetCore(string token, JwsAlgorithm alg, byte[]?key)
        {
            return(Jose.JWT.Decode <Dictionary <string, object> >(token, key: key, alg: alg /*JwsAlgorithm.HS256*/));
        }
Ejemplo n.º 28
0
 public IDictionary <string, object> GetPayLoad(string token, string secretKey, JwsAlgorithm jwsAlgorithm = JwsAlgorithm.HS256)
 {
     if (ValidateToken(token, secretKey, jwsAlgorithm))
     {
         var secret  = Encoding.UTF8.GetBytes(secretKey);
         var payload = Jose.JWT.Decode <IDictionary <string, object> >(token, secret, jwsAlgorithm);
         return(payload);
     }
     return(null);
 }
Ejemplo n.º 29
0
        public string GenerateToken(IDictionary <string, object> headers, IDictionary <string, object> payload, string secretKey, JwsAlgorithm jwsAlgorithm = JwsAlgorithm.HS256)
        {
            if (string.IsNullOrEmpty(secretKey))
            {
                throw new AuthException("未配置secretKey");
            }
            var    secret = Encoding.UTF8.GetBytes(secretKey);
            string token  = Jose.JWT.Encode(payload, secret, jwsAlgorithm, extraHeaders: headers);

            return(token);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Serialize and encodes object to JWT token and sign it using given algorithm.
 /// Json string to encode will be obtained via configured IJsonMapper implementation.
 /// </summary>
 /// <param name="payload">object to map to json string and encode</param>
 /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
 /// <returns>JWT in compact serialization form, digitally signed.</returns>
 public static string Encode(object payload, object key, JwsAlgorithm algorithm)
 {
     return(Encode(jsMapper.Serialize(payload), key, algorithm));
 }