Ejemplo n.º 1
0
        // Encoding with JWT.NET is safe

        void DecodingWithDecoder(JwtDecoder decoder)
        {
            var decoded1 = decoder.Decode(invalidToken, secret, true);
            var decoded2 = decoder.Decode(invalidToken, secret, false); // Noncompliant {{Use only strong cipher algorithms when verifying the signature of this JWT.}}

            var decoded3 = decoder.Decode(invalidToken, secret, verify: true);
            var decoded4 = decoder.Decode(invalidToken, secret, verify: false); // Noncompliant

            var decoded5 = decoder.Decode(invalidToken, secret, verify: true);
            var decoded6 = decoder.Decode(invalidToken, secret, verify: false); // Noncompliant

            var decoded7 = decoder.Decode(invalidToken, verify: true, key: secret);
            var decoded8 = decoder.Decode(invalidToken, verify: false, key: secret); // Noncompliant

            var decoded9  = decoder.Decode(invalidToken, verify: true, key: new byte[] { 42 });
            var decoded10 = decoder.Decode(invalidToken, verify: false, key: new byte[] { 42 }); // Noncompliant

            var decoded11 = decoder.Decode(invalidToken);                                        // Noncompliant
            var decoded12 = decoder.Decode(invalidParts);                                        // Noncompliant

            var decoded21 = decoder.DecodeToObject(invalidToken, secret, true);
            var decoded22 = decoder.DecodeToObject(invalidToken, secret, false); // Noncompliant

            var decoded31 = decoder.DecodeToObject <UserInfo>(invalidToken, secret, true);
            var decoded32 = decoder.DecodeToObject <UserInfo>(invalidToken, secret, false); // Noncompliant
        }
Ejemplo n.º 2
0
        public static JwtPayload ToJwtDecodedPayload(this HttpRequest request, string secret)
        {
            bool result = request.Headers.TryGetValue("Authorization", out var headers);

            if (!result)
            {
                return(null);
            }
            string authHeader = headers.FirstOrDefault();
            var    authBits   = authHeader.Split(' ');

            if (authBits.Length != 2)
            {
                return(null);
            }
            if (!authBits[0].ToLowerInvariant().Equals("bearer"))
            {
                return(null);
            }
            string            token      = authBits[1];
            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);

            return(decoder.DecodeToObject <JwtPayload>(token, secret, verify: false));
        }
Ejemplo n.º 3
0
        public static UserInformation?GetUserInformation(this HttpContext context)
        {
            if (context.Items.TryGetValue("logininfo", out var tmp))
            {
                return(tmp as UserInformation);
            }

            if (!context.Request.Headers.TryGetValue("Authorization", out var value))
            {
                return(null);
            }

            var token = value.Where(it => it.StartsWith("Bear ")).FirstOrDefault();

            if (token == null)
            {
                return(null);
            }
            try
            {
                var payload = jwtDecoder.DecodeToObject <UserInformation>(token.Substring("Bear ".Length));
                return(payload);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 4
0
        public TBody GetBody()
        {
            //  获取 密钥
            string secret = SecretBuilder.Build();

            if (string.IsNullOrWhiteSpace(secret))
            {
                throw new Exception("应用程序密钥(AppSecret)为空或null");
            }

            ICookieFactory cookieFactory = new CookieFactory();
            ICookieClient  cookieClient  = cookieFactory.Create();

            if (!cookieClient.Contains(AuthConfigProvider.AuthConfig.CookieName))
            {
                return(null);
            }

            // 获取cookie, 并解密 数据
            string            token            = cookieClient.GetCookie(AuthConfigProvider.AuthConfig.CookieName);
            IAlgorithmFactory algorithmFactory = new HMACSHAAlgorithmFactory();
            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, algorithmFactory);
            TBody             authUser         = decoder.DecodeToObject <TBody>(token, secret, true);

            SignIn(authUser);

            return(authUser);
        }
Ejemplo n.º 5
0
 public static bool VaildateToken(string tokenkey, out TokenInfo json)
 {
     if (!string.IsNullOrEmpty(tokenkey))
     {
         try
         {
             string            token      = DESEncrypt.DesDecrypt(tokenkey);
             byte[]            key        = Encoding.UTF8.GetBytes(secret);
             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);
             string            result     = decoder.Decode(token, key, true);
             json = decoder.DecodeToObject <TokenInfo>(token, key, true);
             if (json != null)
             {
                 return(true);
             }
         }
         catch (Exception e)
         {
             // ignored
         }
     }
     json = null;
     return(false);
 }
Ejemplo n.º 6
0
        public void DecodeToObject_Should_Throw_Exception_On_Expired_Claim()
        {
            const string key       = TestData.Key;
            const int    timeDelta = -1;

            var algorithm        = new HMACSHA256Algorithm();
            var dateTimeProvider = new UtcDateTimeProvider();
            var serializer       = new JsonNetSerializer();

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

            var now = dateTimeProvider.GetNow();
            var exp = UnixEpoch.GetSecondsSince(now.AddHours(timeDelta));

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

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

            decodeExpiredJwt.Should()
            .Throw <TokenExpiredException>("because decoding an expired token should raise an exception when verified");
        }
Ejemplo n.º 7
0
        public static UserInfo DecodeJWTToken(string jwtToken)
        {
            try
            {
                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);
                UserInfo          dd         = decoder.DecodeToObject <UserInfo>(jwtToken, TokenSecretKey, true);

                return(dd);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
                return(null);
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
                return(null);
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// 根据jwtToken  获取实体
 /// </summary>
 /// <param name="token">jwtToken</param>
 /// <returns></returns>
 public static string GetJwtDecode(string token)
 {
     try
     {
         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);
         //token为之前生成的字符串
         var userInfo = decoder.DecodeToObject(token, secret, verify: true);
         //此处json为IDictionary<string, object> 类型
         string   username = userInfo["username"].ToString(); //可获取当前用户名
         DateTime timeout  = (DateTime)userInfo["timeout"];   //获取token过期时间
         if (timeout < DateTime.Now)
         {
             throw new TokenExpiredException("Token过期,请重新登陆");
         }
         userInfo.Remove("timeout");
         return("OK");
     }
     catch (TokenExpiredException tokenEx)
     {
         return("[Error]Token过期:--" + tokenEx.Message);
     }
     catch (SignatureVerificationException tokenEx)
     {
         return("[Error] 无效的Token:--" + tokenEx.Message);
     }
     catch (Exception ex)
     {
         return("[Error]:" + ex.Message);
     }
 }
Ejemplo n.º 9
0
        public static object Get(string token, string tokenKey, string jsonKey)
        {
            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                string json = decoder.Decode(token, tokenKey, verify: true);

                var dic = decoder.DecodeToObject <Dictionary <string, object> >(token);

                return(dic[jsonKey]);
            }
            catch (TokenExpiredException ex)
            {
                throw new BaseException("请重新登陆,token已失效");
            }
            catch (SignatureVerificationException ex)
            {
                throw new BaseException("请重新登陆,签名错误");
            }
        }
Ejemplo n.º 10
0
        private void VerifyJsonWebToken()
        {
            JsonNetSerializer   jsonNetSerializer   = new JsonNetSerializer();
            UtcDateTimeProvider utcDateTimeProvider = new UtcDateTimeProvider();
            JwtBase64UrlEncoder jwtBase64UrlEncoder = new JwtBase64UrlEncoder();
            JwtValidator        jwtValidator        = new JwtValidator(jsonNetSerializer, utcDateTimeProvider);

            JwtDecoder jwtDecoder = new JwtDecoder(jsonNetSerializer, jwtValidator, jwtBase64UrlEncoder);

            try
            {
                IDictionary <string, object> payloadClaims = jwtDecoder.DecodeToObject(JsonWebToken, CommunicationKey, true);

                if (!payloadClaims.ContainsKey(IssAtClaims) || !payloadClaims.ContainsKey(ApplicationIdClaims) ||
                    !payloadClaims[ApplicationIdClaims].ToString().Equals(ApplicationId, StringComparison.OrdinalIgnoreCase))
                {
                    throw new Exception("Jwt中Payload不符合规范");
                }

                IsRequestExpire((long)payloadClaims[IssAtClaims]);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("身份认证失败:{0}", e.Message));
            }
        }
Ejemplo n.º 11
0
        public static void verifyToken(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);

                string json = decoder.Decode(token, secret, verify: true);
                Console.WriteLine(json);

                var payload = decoder.DecodeToObject <IDictionary <string, object> >(token);
                Console.WriteLine(payload["id"]);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("令牌已过期");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("令牌的签名无效");
            }
        }
Ejemplo n.º 12
0
        public static Boolean CheckTokenValidation(string token)
        {
            var               tokenAccess = Convert.ToString(Xamarin.Forms.Application.Current.Properties["token"]);
            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);

            if (tokenAccess != null)
            {
                var json = decoder.DecodeToObject(tokenAccess);
                if (json.TryGetValue("exp", out object expiryObj))
                {
                    var exp  = Convert.ToInt32(expiryObj);
                    var date = DateTimeOffset.FromUnixTimeSeconds(exp).DateTime;
                    if (date <= DateTime.Now)
                    {
                        return(false);
                    }
                    return(true);
                }
                else
                {
                    throw new Exception("");
                }
            }
            throw new Exception();
        }
Ejemplo n.º 13
0
        //token feali ro tabdil mikone be data
        public CurrentUserInfo GetUserInfo()
        {
            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);

                IDictionary <string, string> userDataDictionary = decoder.DecodeToObject <IDictionary <string, string> >(UserToken(), Secret, true);

                return(new CurrentUserInfo
                {
                    Id = int.Parse(userDataDictionary["Id"]),
                    Username = userDataDictionary["UserName"],
                    Password = userDataDictionary["Password"],
                    Role = userDataDictionary["Role"]
                });
            }
            catch (TokenExpiredException)
            {
                //igonre exception
                return(null);
            }
            catch (SignatureVerificationException)
            {
                //igonre exception
                return(null);
            }
        }
Ejemplo n.º 14
0
        private static LoginData DecryptToken(String token)
        {
            if (String.IsNullOrWhiteSpace(token))
            {
                throw new SignatureVerificationException("Invalid token");
            }

            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);

            Dictionary <String, Object> payload = decoder.DecodeToObject <Dictionary <String, Object> >(token, _serverToken, verify: true);

            if (payload == null || !payload.ContainsKey("exp") || !payload.ContainsKey("userid") || !payload.ContainsKey("name"))
            {
                throw new SignatureVerificationException("Incomplete token");
            }

            Int32.TryParse(payload["exp"].ToString(), out Int32 expiresInSeconds);

            LoginData loginData = new LoginData();

            loginData.UserId            = payload["userid"].ToString();
            loginData.UserDisplayName   = payload["name"].ToString();
            loginData.ExpirationSeconds = Math.Max(GetSecondsToExpiration(expiresInSeconds), -1);

            return(loginData);
        }
Ejemplo n.º 15
0
        public HttpResponseMessage login(string account, string password)
        {
            User user             = userDal.login(account, password);
            HttpResponseMessage h = new HttpResponseMessage();

            if (user == null)
            {
                h.Content = new StringContent(JsonConvert.SerializeObject(new { stasus = 0, message = "用户名或密码错误" }), Encoding.GetEncoding("UTF-8"), "application/json");
            }
            else
            {
                System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("token")
                {
                    Value   = user.Token,
                    Expires = user.Entry_time
                });
                const string      secret     = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";
                byte[]            key        = Encoding.UTF8.GetBytes(secret);
                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 <Models.Auth>(user.Token, key, verify: true);
                h.Content = new StringContent(JsonConvert.SerializeObject(new { json, stasus = 1, user }), Encoding.GetEncoding("UTF-8"), "application/json");
            }
            return(h);
        }
Ejemplo n.º 16
0
        public static bool TryValidateToken(string token, out ClaimsPrincipal principal)
        {
            var symmetricKey = Convert.FromBase64String(Secret);

            principal = null;
            var result = false;

            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          payload = decoder.DecodeToObject(token, symmetricKey, true);
                List <Claim> claims  = new List <Claim>();
                foreach (var item in payload)
                {
                    if (item.Value == null)
                    {
                        continue;
                    }

                    var key   = item.Key;
                    var value = item.Value.ToString();
                    if (key.ToLower() == "name")
                    {
                        claims.Add(new Claim(ClaimTypes.Name, value));
                    }
                    else if (key.ToLower() == "role")
                    {
                        claims.Add(new Claim(ClaimTypes.Role, value));
                    }
                    else
                    {
                        claims.Add(new Claim(key, value));
                    }
                }

                var identity = new ClaimsIdentity(claims, "JWT");
                principal = new ClaimsPrincipal(identity);
                result    = true;
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(result);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// 解密RS256
 /// </summary>
 /// <param name="token"></param>
 /// <param name="secret"></param>
 /// <param name="exponent"></param>
 /// <param name="modulus"></param>
 /// <returns></returns>
 private static IDictionary <string, object> DecodeRs256(string token, string secret, string exponent, string modulus)
 {
     try
     {
         IJsonSerializer   serializer = new JsonNetSerializer();
         IDateTimeProvider provider   = new UtcDateTimeProvider();
         IJwtValidator     validator  = new JwtValidator(serializer, provider);
         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
         var rS256Algorithm           = new RSAlgorithmFactory(() =>
         {
             var rsa = new RSACryptoServiceProvider();
             rsa.ImportParameters(
                 new RSAParameters()
             {
                 Modulus  = FromBase64Url(modulus),
                 Exponent = FromBase64Url(exponent)
             });
             byte[] rsaBytes = rsa.ExportCspBlob(true);
             var cert        = new X509Certificate2(rsaBytes);
             return(cert);
         });
         IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, rS256Algorithm);
         var         json    = decoder.DecodeToObject(token, secret, verify: false);
         return(json);
     }
     catch (TokenExpiredException ex)
     {
         throw new InvalidOperationException("token已过期", ex);
     }
     catch (SignatureVerificationException ex)
     {
         throw new InvalidOperationException("token验证失败", ex);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 使用自定义的密钥解密JWT文本,HS512签名
        /// </summary>
        /// <param name="strSecretKey">密钥</param>
        /// <param name="strSecretMsg">需要解密的文本</param>
        /// <returns></returns>
        public static object DecodeByJwt(string strSecretKey, string strSecretMsg)
        {
            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(strSecretMsg, strSecretKey, verify: true);
                //return json;

                var payload = decoder.DecodeToObject <IDictionary <string, object> >(strSecretMsg, strSecretKey, true);
                return(payload["Crypt"]);
            }
            catch (TokenExpiredException)
            {
                throw new Exception("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                throw new Exception("Token has invalid signature");
            }
        }
        private bool CheckCookie()
        {
            var accessToken = HttpContext.Request.Cookies["access_token"];


            IJsonSerializer   _serializer = new JsonNetSerializer();
            IDateTimeProvider _provider   = new UtcDateTimeProvider();
            IBase64UrlEncoder _urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm     _algorithm  = new HMACSHA256Algorithm();

            try
            {
                IJwtValidator  _validator     = new JwtValidator(_serializer, _provider);
                IJwtDecoder    decoder        = new JwtDecoder(_serializer, _validator, _urlEncoder, _algorithm);
                var            token          = decoder.DecodeToObject <JwtToken>(accessToken);
                DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(token.exp);
                DateTimeOffset now            = DateTimeOffset.Now;

                return(dateTimeOffset < now);
            }
            catch (TokenExpiredException)
            {
                return(true);
            }
            catch (SignatureVerificationException)
            {
                return(true);
            }
            catch (Exception)
            {
                return(true);
            }
        }
        public static DecodedToken DecodeToken(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);
                var payload = decoder.DecodeToObject <UserViewModel>(token, _secret, true);

                return(new DecodedToken {
                    IsValid = true, TokenJson = payload, TokenString = json
                });
            }
            catch (TokenExpiredException)
            {
                return(new DecodedToken {
                    IsValid = false, ErrorMsg = "Token has expired"
                });
            }
            catch (SignatureVerificationException)
            {
                return(new DecodedToken {
                    IsValid = false, ErrorMsg = "Token has invalid signature"
                });
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Token解密
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static IDictionary <string, object> DecodeToken(string token)
        {
            IDictionary <string, object> dic = new Dictionary <string, object>();

            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);

                dic = decoder.DecodeToObject(token);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }

            return(dic);
        }
Ejemplo n.º 22
0
        public static OAuthModel GetUser(HttpContext context)
        {
            if (!IsAuthenticated(context))
            {
                return(null);
            }

            var token = context.Request.Cookies[CookieName];

            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            var key = Encoding.ASCII.GetBytes(SecretKey);

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

            var user = decoder.DecodeToObject <OAuthModel>(token, key, false);

            return(user);
        }
Ejemplo n.º 23
0
        private AuthInfo ValidateTicket(HttpActionContext actionContext)
        {
            AuthInfo auinfo     = null;
            var      authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                const string secretKey = "Hello World";               //加密秘钥
                string       token     = authHeader.FirstOrDefault(); //获取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();
                    var         algorithm        = new HMACSHA256Algorithm();
                    IJwtDecoder decoder          = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                    //解密
                    auinfo = decoder.DecodeToObject <AuthInfo>(token, key, verify: true);
                    ////管道传参
                    var obj = new { username = auinfo.UserName, usercode = "testcode" };
                    HttpContext.Current.Items["UserName"] = obj;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(auinfo);
        }
Ejemplo n.º 24
0
        public static JwtDecode <T> Decode <T>(string token, string secret)
        {
            JwtDecode <T> jwtDecodeInfo = new JwtDecode <T>
            {
                VerifyResult = JwtVerifyResult.Fail
            };

            try
            {
                var jns = new JsonNetSerializer();
                IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider();
                IJwtValidator     jwtValidator     = new JwtValidator(jns, dateTimeProvider);
                IBase64UrlEncoder base64UrlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       jwtDecoder       = new JwtDecoder(jns, jwtValidator, base64UrlEncoder);
                jwtDecodeInfo.Payload      = jwtDecoder.DecodeToObject <T>(token, secret, true);
                jwtDecodeInfo.VerifyResult = JwtVerifyResult.Succeed;
            }
            catch (TokenExpiredException)
            {
                jwtDecodeInfo.VerifyResult = JwtVerifyResult.Expired;
                jwtDecodeInfo.Msg          = "Token已过期";
            }
            catch (SignatureVerificationException)
            {
                jwtDecodeInfo.VerifyResult = JwtVerifyResult.InvalidSignature;
                jwtDecodeInfo.Msg          = "Token签名无效";
            }
            return(jwtDecodeInfo);
        }
Ejemplo n.º 25
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                string token = authHeader.FirstOrDefault();
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        const string secret = "To Live is to change the world";
                        //secret需要加密
                        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, secret, verify: true);
                        if (json != null)
                        {
                            actionContext.RequestContext.RouteData.Values.Add("auth", json);
                            return(true);
                        }
                        return(false);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 26
0
        private void webBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            if (e.Uri.Fragment.StartsWith("#url=") && e.Uri.Fragment.Contains("&error=1"))
            {
                this.HandleWrongUrl(e.Uri.Fragment);
                return;
            }

            if (!e.Uri.AbsoluteUri.StartsWith("http://localhost/#"))
            {
                return;
            }

            var parameters = new ParameterCollection(e.Uri.Fragment.Substring(1));

            this.AccessToken = parameters["access_token"];

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

            var payload = decoder.DecodeToObject(this.AccessToken);

            this.UserName = payload["username"].ToString();
            this.Server   = payload["ws"].ToString();

            this.DialogResult = true;
            this.Close();
        }
Ejemplo n.º 27
0
        public static IDictionary <string, object> Decode(string token, string secret, string salt, int iter)
        {
            IDictionary <string, object> rdict = new Dictionary <string, object>();

            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, new HMACSHA256Algorithm());

                var dict = decoder.DecodeToObject <IDictionary <string, object> >(token, NewKey(secret, salt, iter), verify: true);

                return(dict);
            }
            catch (TokenExpiredException)
            {
                rdict["Error"] = "Token has expired";
                return(rdict);
            }
            catch (SignatureVerificationException)
            {
                rdict["Error"] = "Token has invalid signature";
                return(rdict);
            }
        }
Ejemplo n.º 28
0
        public void Decode_Token_To_Obj()
        {
            var         decoder = new JwtDecoder(new JsonNetSerializer(), null, new Base64UrlEncoder());
            Func <User> func    = () => decoder.DecodeToObject <User>(token, secret, false);
            var         user    = func();

            Assert.NotNull(user);
        }
Ejemplo n.º 29
0
        public void DecodeToObject_Should_Throw_Exception_On_Malformed_Token()
        {
            var serializer = new JsonNetSerializer();
            var decoder    = new JwtDecoder(serializer, null);

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

            action.ShouldThrow <ArgumentException>();
        }
Ejemplo n.º 30
0
        public static Ret <bool> CheckJwt(string jwt)
        {
            var jwtMain = jwt.Replace("bear ", "", StringComparison.OrdinalIgnoreCase);

            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 payloadRet = GetPayload(jwtMain);

            if (!payloadRet.IsNormal)
            {
                return(new Ret <bool>(string.Format($"token={jwt},{payloadRet.ExceptionMsg}"), null, false));
            }

            var payload = payloadRet.Data;
            var bizName = payload.Iss;

            var reqestInfo = string.Format($"BizName={bizName}");

            try
            {
                decoder.DecodeToObject <JyPayload>(jwtMain, new RealKey(bizName, _baseJwtKey).ToString(), verify: true);

                long expTime;
                if (!long.TryParse(payload.Exp, out expTime))
                {
                    return(new Ret <bool>(string.Format($"Exp={payload.Exp}的值无效!"), null, false));
                }

                var nowTime = GetTimeStamp(DateTime.UtcNow);
                if (expTime < nowTime)
                {
                    return(new Ret <bool>(
                               string.Format(
                                   $"Exp={payload.Exp}小于当前时间{nowTime},已过期!"),
                               null, false));
                }

                //验证通过
                return(new Ret <bool>(true, "", "", true));
            }
            catch (TokenExpiredException tee)
            {
                return(new Ret <bool>(string.Format($"{reqestInfo}. token={jwt}"), tee, false));
            }
            catch (SignatureVerificationException sve)
            {
                return(new Ret <bool>(string.Format($"{reqestInfo}. token={jwt}"), sve, false));
            }
            catch (Exception ex)
            {
                return(new Ret <bool>(string.Format($"{reqestInfo}. token={jwt}"), ex, false));
            }
        }