Example #1
0
        public void DecodeToObject_Should_Decode_Token_To_Dictionary_Multiple_Secrets()
        {
            var          expected = TestData.DictionaryPayload;
            const string key      = TestData.Key;
            const string token    = TestData.Token;

            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            var actual = decoder.DecodeToObject(token, new[] { key }, verify: true);

            actual.Should()
            .Equal(expected, "because the JWT should have been correctly deserialized to the correct object");
        }
Example #2
0
 public static string GetTokenJson(string token)
 {
     try
     {
         IJsonSerializer   serializer = new JsonNetSerializer();
         IDateTimeProvider provider   = new UtcDateTimeProvider();
         IJwtValidator     validator  = new JwtValidator(serializer, provider);
         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
         IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);
         var json = decoder.Decode(token, SecretKey, verify: true);
         return(json);
     }
     catch (Exception)
     {
         throw;
     }
 }
Example #3
0
        public void DecodeToObject_Should_Decode_Token_To_Generic_Type_Multiple_Secrets()
        {
            var          expected = TestData.Customer;
            const string key      = TestData.Key;
            const string token    = TestData.Token;

            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            var actual = decoder.DecodeToObject <Customer>(token, new[] { key }, verify: true);

            actual.Should()
            .BeEquivalentTo(expected, "because the JWT should have been correctly deserialized to the same customer object");
        }
        public static bool ValidateToken(string token)
        {
            IJwtValidator validator = new JwtValidator(_serializer, _provider);

            IJwtDecoder decoder = new JwtDecoder(_serializer, validator, _urlEncoder);

            try
            {
                decoder.Decode(token, secret, verify: true);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Example #5
0
        public T Decode <T>(string token, string secret)
        {
            var serializer = new JsonNetSerializer();
            var base64     = new JwtBase64UrlEncoder();
            var provier    = new UtcDateTimeProvider();
            var validator  = new JwtValidator(serializer, provier);

            var payload = new JwtBuilder()
                          .WithSerializer(serializer)
                          .WithValidator(validator)
                          .WithUrlEncoder(base64)
                          .WithSecret(secret)
                          .MustVerifySignature()
                          .Decode <T>(token);

            return(payload);
        }
Example #6
0
        public void DecodeToObject_Should_Throw_Exception_On_Invalid_Key_Multiple_Secrets()
        {
            const string token = TestData.Token;
            var          keys  = _fixture.Create <string[]>();

            var serializer = new JsonNetSerializer();
            var validTor   = new JwtValidator(serializer, new UtcDateTimeProvider());
            var urlEncoder = new JwtBase64UrlEncoder();
            var decoder    = new JwtDecoder(serializer, validTor, urlEncoder);

            Action decodingAJwtWithWrongKey = ()
                                              => decoder.DecodeToObject <Customer>(token, keys, verify: true);

            decodingAJwtWithWrongKey.Should()
            .Throw <SignatureVerificationException>(
                "because providing the wrong key must raise an error when the signature is verified");
        }
Example #7
0
        public DTO.Tokens.JWT Decode(string Token = "")
        {
            if (string.IsNullOrWhiteSpace(Token))
            {
                return(null);
            }

            IJsonSerializer   serializer = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            var json = decoder.Decode(Token, Secret, true);

            return(JSON.Deserialize <DTO.Tokens.JWT>(json));
        }
Example #8
0
 /// <summary>
 /// 根据jwtToken  获取实体
 /// </summary>
 /// <param name="token">jwtToken</param>
 /// <returns></returns>
 public static T Get <T>(string token)
 {
     try
     {
         IJsonSerializer   serializer = new JsonNetSerializer();
         IDateTimeProvider provider   = new UtcDateTimeProvider();
         IJwtValidator     validator  = new JwtValidator(serializer, provider);
         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
         IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);
         var userInfo = decoder.DecodeToObject <T>(token, WebConfig.JWT_Secret, verify: true);//token为之前生成的字符串
         return(userInfo);
     }
     catch (Exception ex)
     {
         return(default(T));
     }
 }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            //从网络请求中获取到token
            //用相同的解密方式,判断请求过来的token是不是复合规范
            //符合 验证通过
            //不符合要求 验证失败
            //在Api中使用权限过滤器,过滤请求的请求头中间是否包含key=token
            //如果包含则验证token的值是否正确(token是不是在api中获取的,tpken是否过期),不包含返回失败

            var authHeader = from t in actionContext.Request.Headers where t.Key == "token" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        const string secret = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4aKpVo2OHXPwb1R7duLgg";
                        //secret需要加密
                        IJsonSerializer   serializer = new JsonNetSerializer();
                        IDateTimeProvider provider   = new UtcDateTimeProvider();
                        IJwtValidator     validator  = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();


                        IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                        var json = decoder.DecodeToObject <object>(token, secret, verify: true);
                        if (json != null)
                        {
                            actionContext.RequestContext.RouteData.Values.Add("auth", json);
                            return(true);
                        }
                        return(false);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Example #10
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            string token = null;

            //读取请求中是否包含token
            if (actionContext.Request.Headers.TryGetValues("Authorization", out IEnumerable <string> headValues))
            {
                token = headValues.FirstOrDefault();
            }

            if (token != null)
            {
                try
                {
                    //验证jwt的合法性
                    IJsonSerializer   serializer = new JsonNetSerializer();
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                    IDateTimeProvider provider   = new UtcDateTimeProvider();
                    IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                    IJwtValidator     validator  = new JwtValidator(serializer, provider);
                    IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                    var json = decoder.Decode(token, ConfigurationManager.AppSettings["JwtSecret"], verify: true);

                    //验证redis是否过期
                    if (RedisHelper.Get(token) == null)
                    {
                        HttpResponseMessage httpResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                        httpResponse.Content   = new StringContent("签名已过期");
                        actionContext.Response = httpResponse;
                    }
                }
                catch (SignatureVerificationException)
                {
                    HttpResponseMessage httpResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    httpResponse.Content   = new StringContent("签名无效");
                    actionContext.Response = httpResponse;
                }
            }
            else
            {
                HttpResponseMessage httpResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                httpResponse.Content   = new StringContent("签名无效");
                actionContext.Response = httpResponse;
            }
        }
        static void Main(string[] args)
        {
            var payload = new Dictionary <string, object>
            {
                { "UserId", "hx123456" },
                { "UserName", "admin" }
            };
            var               secret     = "ASDFQWEFAWDFASDFASGERGSDRGFSDFGSDFGERTGWER";//不要泄露
            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            var token = encoder.Encode(payload, secret);

            Console.WriteLine(token);

            try
            {
                IDateTimeProvider provider  = new UtcDateTimeProvider();
                IJwtValidator     validator = new JwtValidator(serializer, provider);
                IJwtDecoder       decoder   = new JwtDecoder(serializer, validator, urlEncoder);

                var json = decoder.Decode(token, secret, verify: true);
                Console.WriteLine(json);
            }
            catch (FormatException e)
            {
                Console.WriteLine("Token format invalid" + e.Message);
            }
            catch (TokenExpiredException e)
            {
                Console.WriteLine("Token has expired" + e.Message);
            }
            catch (SignatureVerificationException e)
            {
                Console.WriteLine("Token has invalid signature" + e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("Hello World!");
        }
Example #12
0
        public static T GetDecryptToken <T>(string jwtToken, string key)
        {
            T model = Activator.CreateInstance <T>();

            IJsonSerializer serializer = new JsonNetSerializer();

            IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider();

            IJwtValidator validate = new JwtValidator(serializer, dateTimeProvider);

            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

            IJwtDecoder decode = new JwtDecoder(serializer, validate, urlEncoder);

            model = decode.DecodeToObject <T>(jwtToken, key, true);

            return(model);
        }
Example #13
0
        /// <summary>
        /// Create the default set of JwtServiceArgs
        /// </summary>
        /// <param name="useDefaults">If the JWT Service should use defaults</param>
        /// <param name="loggingService">The logging service to log errors with, default null</param>
        /// <param name="secureSecret">The secure secret used to encode JWTs, default null</param>
        public JwtServiceArgs(bool useDefaults, ILoggingService loggingService = null, SecureString secureSecret = null)
        {
            if (useDefaults)
            {
                Serializer = new JsonNetSerializer();
                Provider   = new UtcDateTimeProvider();
                UrlEncoder = new JwtBase64UrlEncoder();
                Algorithm  = new HMACSHA256Algorithm();
                Secret     = Environment.GetEnvironmentVariable("JWT_SECRET");

                Validator = new JwtValidator(Serializer, Provider);
                Decoder   = new JwtDecoder(Serializer, Validator, UrlEncoder);
                Encoder   = new JwtEncoder(Algorithm, Serializer, UrlEncoder);
            }

            LoggingService = loggingService;
            SecureSecret   = secureSecret;
        }
Example #14
0
        public static bool IsValidToken(string token)
        {
            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                var json = decoder.Decode(token, secret, verify: true);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #15
0
        private static Dictionary <string, string> DecodeJwt(string token)
        {
            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                var json = decoder.Decode(token, GetSecret(), verify: true);
                return(JsonConvert.DeserializeObject <Dictionary <string, string> >(json));
            }
            catch (Exception)
            {
                return(new Dictionary <string, string>());
            }
        }
Example #16
0
        public static bool VerifyToken(string token, string key, string value = "true")
        {
            IJsonSerializer   serializer = new JsonSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            string json = decoder.Decode(token, Secret, true);
            Dictionary <string, string> claims = serializer.Deserialize <Dictionary <string, string> >(json);

            if (claims.ContainsKey(key) && claims[key] == value)
            {
                return(true);
            }

            return(false);
        }
Example #17
0
        public void Init()
        {
            var serializer = new JsonNetSerializer();
            var validator  = new JwtValidator(serializer, new UtcDateTimeProvider());

            jwtDecoder = new JwtDecoder(serializer, validator, new JwtBase64UrlEncoder());

            Constants.JwtValidIssuer     = "TestIssuer";
            Constants.JwtValidAudience   = "TestAudience";
            Constants.JwtSecretKey       = "test-gv-core-secret-key";
            Constants.JwtExpiryInMinutes = 10;

            user = new ApplicationUser
            {
                Id       = Guid.NewGuid(),
                UserName = "******"
            };
        }
Example #18
0
        public void Decode_Should_Decode_Token_To_Json_String_Multiple_Secrets()
        {
            const string key         = TestData.Key;
            const string token       = TestData.Token;
            var          toSerialize = TestData.Customer;

            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            var actual   = decoder.Decode(token, new[] { key }, verify: true);
            var expected = serializer.Serialize(toSerialize);

            actual.Should()
            .Be(expected, "because the provided object should be correctly serialized in the token");
        }
Example #19
0
        public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim()
        {
            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            var now = dateTimeProvider.GetNow();
            var exp = (int)(now.AddHours(-1) - JwtValidator.UnixEpoch).TotalSeconds;

            var encoder      = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var expiredtoken = encoder.Encode(new { exp = exp }, "ABC");

            Action action = () => decoder.DecodeToObject <Customer>(expiredtoken, "ABC", verify: true);

            action.ShouldThrow <TokenExpiredException>();
        }
Example #20
0
        public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim()
        {
            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var decoder          = new JwtDecoder(serializer, validator);

            var now           = dateTimeProvider.GetNow();
            var hourAgo       = now.Subtract(new TimeSpan(1, 0, 0));
            var unixTimestamp = (int)(hourAgo - new DateTime(1970, 1, 1)).TotalSeconds;

            var encoder      = new JwtEncoder(new HMACSHA256Algorithm(), serializer);
            var expiredtoken = encoder.Encode(new { exp = unixTimestamp }, "ABC");

            Action action = () => decoder.DecodeToObject <Customer>(expiredtoken, "ABC", verify: true);

            action.ShouldThrow <TokenExpiredException>();
        }
Example #21
0
        public void Decode_Should_Throw_Exception_When_HMA_Algorithm_Is_Used_But_RSA_Was_Expected_MultipleKeys()
        {
            var serializer = new JsonNetSerializer();
            var urlEncoder = new JwtBase64UrlEncoder();
            var encoder    = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);

            var encodedToken = encoder.Encode(TestData.Customer, TestData.ServerRsaPublicKey1);

            var validTor   = new JwtValidator(serializer, new UtcDateTimeProvider());
            var algFactory = new RSAlgorithmFactory(() => new X509Certificate2(TestData.ServerRsaPublicKey1));
            var decoder    = new JwtDecoder(serializer, validTor, urlEncoder, algFactory);

            Action decodeJwtWithRsaWhenHmaIsExpected =
                () => decoder.Decode(encodedToken, TestData.ServerRsaPublicKeys, verify: true);

            decodeJwtWithRsaWhenHmaIsExpected.Should()
            .Throw <NotSupportedException>("because an encryption algorithm can't be changed another on decoding");
        }
Example #22
0
        /// <summary>
        /// 解析token提取用户授权信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public AuthInfo DecodeToken(string token)
        {
            string   secret   = System.Configuration.ConfigurationManager.AppSettings["SecureKey"];
            AuthInfo authInfo = null;

            IJsonSerializer   serializer = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            try
            {
                authInfo = decoder.DecodeToObject <AuthInfo>(token, secret, verify: true);
            }
            catch { }
            return(authInfo);
        }
Example #23
0
        public void DecodeToObject_Should_Throw_Exception_Before_NotBefore_Becomes_Valid()
        {
            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validTor         = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validTor, urlEncoder);

            var now = dateTimeProvider.GetNow();
            var nbf = UnixEpoch.GetSecondsSince(now.AddHours(1));

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { nbf }, "ABC");

            Action action = () => decoder.DecodeToObject <Customer>(token, "ABC", verify: true);

            Assert.Throws <SignatureVerificationException>(action);
        }
        /// <summary>
        /// 验证token
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var authHeader = from t in actionContext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                string secretKey = "JWT SECRET";                //口令加密秘钥
                string token     = authHeader.FirstOrDefault(); //获取token
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        byte[]            key        = Encoding.UTF8.GetBytes(secretKey);
                        IJsonSerializer   serializer = new JsonNetSerializer();
                        IDateTimeProvider provider   = new UtcDateTimeProvider();
                        IJwtValidator     validator  = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);
                        //解密
                        var json = decoder.DecodeToObject <Payload>(token, key, verify: true);
                        if (json.ExpiryDateTime < DateTime.Now)
                        {
                            return(false);
                        }

                        actionContext.RequestContext.RouteData.Values.Add("Authorization", json);
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        log.Error("token生成失败:" + ex.Message);
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Example #25
0
        public Task Invoke(HttpContext context)
        {
            var authHeader = from t in context.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                const string secretKey = "Hello World";//加密秘钥
                string       token     = authHeader.FirstOrDefault();
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        byte[]            key        = Encoding.UTF8.GetBytes(secretKey);
                        IJsonSerializer   serializer = new JsonNetSerializer();
                        IDateTimeProvider provider   = new UtcDateTimeProvider();
                        IJwtValidator     validator  = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                        var json = decoder.DecodeToObject <AuthInfo>(token, key, verify: true);

                        if (json != null) //Token验证成功
                        {
                            if (json.ExpiryDateTime < DateTime.Now)
                            {
                                return(_next.Invoke(context));
                                //return context.Response.WriteAsync("Token已失效");
                            }
                            return(_next.Invoke(context));
                        }
                        else //Token验证失败
                        {
                            return(context.Response.WriteAsync("Token验证失败!"));
                        }
                    }
                    catch (Exception ex)
                    {
                        //context.Result = new EmptyResult();
                        return(context.Response.WriteAsync("Token验证发生异常!"));
                    }
                }
            }
            return(context.Response.WriteAsync("authHeader为空!"));
        }
Example #26
0
        public void DecodeToObject_Should_Decode_Token_After_NotBefore_Becomes_Valid()
        {
            var          dateTimeProvider = new UtcDateTimeProvider();
            const string key = TestData.Key;

            var serializer = new JsonNetSerializer();
            var validator  = new JwtValidator(serializer, new UtcDateTimeProvider());

            var urlEncoder = new JwtBase64UrlEncoder();
            var decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            var now = dateTimeProvider.GetNow();
            var nbf = UnixEpoch.GetSecondsSince(now);

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { nbf }, key);

            decoder.DecodeToObject <Customer>(token, key, verify: true);
        }
Example #27
0
        public void DecodeToObject_Should_Throw_Exception_On_Invalid_Expiration_Claim_MultipleKeys()
        {
            const string key = TestData.Key;

            var serializer = new JsonNetSerializer();
            var validator  = new JwtValidator(serializer, new UtcDateTimeProvider());

            var urlEncoder = new JwtBase64UrlEncoder();
            var decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { exp = _fixture.Create <string>() }, key);

            Action encodeJwtWithWrongExpField =
                () => decoder.DecodeToObject <Customer>(token, new[] { key }, verify: true);

            encodeJwtWithWrongExpField.Should()
            .Throw <SignatureVerificationException>("because the invalid 'exp' must result in an exception on decoding");
        }
Example #28
0
        public static UserDTO GetLoginUser()
        {
            ICacheFactory        cacheFactory = ServiceLocator.Get <ICacheFactory>();
            ICacheClient         cacheClient  = cacheFactory.CreateClient(CacheType.Redis);
            IHttpContextAccessor httpContext  = ServiceLocator.Get <IHttpContextAccessor>();
            bool flag = httpContext.HttpContext.Request.Headers.TryGetValue("loginToken", out StringValues token);

            if (!flag)
            {
                throw new AuthException();
            }
            if (string.IsNullOrEmpty(token[0]) || token[0] == "null")
            {
                throw new AuthException();
            }
            string value = cacheClient.StringGet(token);

            #region 判断是否过期
            TokenModel tokenModel = JsonConvert.DeserializeObject <TokenModel>(value);
            if (tokenModel.ExpireTime < DateTime.Now)
            {
                cacheClient.Remove(token);
                throw new AuthException();
            }
            if (DateTime.Now.AddDays(1) == tokenModel.ExpireTime)
            {
                tokenModel.ExpireTime = DateTime.Now.AddDays(7);
                cacheClient.StringSet(token, tokenModel, TimeSpan.FromDays(7));
            }
            #endregion
            if (string.IsNullOrEmpty(value))
            {
                throw new AuthException();
            }
            IJsonSerializer   serializer = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
            var json = decoder.Decode(token);
            return(JsonConvert.DeserializeObject <UserDTO>(json));
        }
        public static IDictionary <string, object> DecodeToken(string token, string secret)
        {
            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                var jsonPayload = decoder.DecodeToObject <IDictionary <string, object> >(token, secret, verify: true);

                return(jsonPayload);
            }
            catch (Exception e) when(e is SignatureVerificationException || e is ArgumentException)
            {
                throw new NotifyAuthException(e.Message);
            }
        }
Example #30
0
        public void Decode_With_Multiple_Secrets_Should_Return_Token()
        {
            const string key     = TestData.Secret;
            const string token   = TestData.Token;
            var          payload = TestData.Customer;

            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm);

            var actual = decoder.Decode(token, new[] { key }, verify: true);

            var expected = serializer.Serialize(payload);

            actual.Should()
            .Be(expected, "because the provided object should be correctly serialized in the token");
        }