예제 #1
0
        /// <summary>
        /// 解析token
        /// <para>作    者:蔡亚康</para>
        /// <para>创建时间:2019-03-06</para>
        /// </summary>
        /// <param name="publicKey">公钥</param>
        /// <param name="token">要解析的token的值</param>
        /// <returns></returns>
        private List <Claim> Decode(string publicKey, string token)
        {
            List <Claim> claims = new List <Claim>();

            using (RSA rsa = RSAKeyHelper.CreateRsaProviderFromPublicKey(publicKey))
            {
                JwtSecurityTokenHandler   handler    = new JwtSecurityTokenHandler();
                TokenValidationParameters validParam = new TokenValidationParameters()
                {
                    IssuerSigningKey = new RsaSecurityKey(rsa),
                    ValidateIssuer   = false,   //不验证颁布者
                    ValidateAudience = false,   //不验证使用者
                    ValidateLifetime = true,
                };
                try
                {
                    SecurityToken jwtSecurityToken = null;
                    handler.ValidateToken(token, validParam, out jwtSecurityToken);
                    JwtSecurityToken jwtSecurityToken2 = jwtSecurityToken as JwtSecurityToken;
                    if (jwtSecurityToken2 != null)
                    {
                        claims.AddRange(jwtSecurityToken2.Claims);
                    }
                    else
                    {
                        LogWriter.Write("JwtTokenService.Decode", "TOKEN解析发生错误,可能是密钥不正确", LoggerType.Error);
                    }
                }
                catch (SecurityTokenDecryptionFailedException ex)
                {
                    LogWriter.Write("JwtTokenService.Decode", "TOKEN解析发生错误", LoggerType.Error);
                }
                catch (SecurityTokenInvalidSignatureException ex)
                {
                    //签名校验失败
                    LogWriter.Write("JwtTokenService.Decode", "签名校验失败", LoggerType.Error);
                }
                catch (SecurityTokenExpiredException ex)
                {
                    //Token过期,status=-9
                    LogWriter.Write("JwtTokenService.Decode", "Token过期", LoggerType.Error);
                }
                catch (Exception ex)
                {
                    //其他异常
                    LogWriter.Write("JwtTokenService.Decode", ex.Message, LoggerType.Error);
                }
                return(claims);
            }
        }
예제 #2
0
        /// <summary>
        /// 创建token
        /// <para>作    者:蔡亚康</para>
        /// <para>创建时间:2019-03-06</para>
        /// </summary>
        /// <param name="user">登陆的用户实体信息</param>
        /// <returns>token值</returns>
        internal String CreateToken(TblHssPassport user)
        {
            string privateKey = ClientConfigManager.HssConfig.TokenKey.PrivateKey;  //使用私钥加密


            int tokenTimestamp = ClientConfigManager.HssConfig.TokenTimestamp;

            RSA rsa = RSAKeyHelper.CreateRsaProviderFromPrivateKey(privateKey);
            //Claims(Payload)
            //       Claims 部分包含了一些跟这个 token 有关的重要信息。 JWT 标准规定了一些字段,下面节选一些字段:

            //iss: The issuer of the token,token 是给谁的
            //       sub: The subject of the token,token 主题
            //       exp: Expiration Time。 token 过期时间,Unix 时间戳格式
            //       iat: Issued At。 token 创建时间, Unix 时间戳格式
            //       jti: JWT ID。针对当前 token 的唯一标识
            //       除了规定的字段外,可以包含其他任何 JSON 兼容的字段。
            var key   = new RsaSecurityKey(rsa);
            var creds = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);

            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(JwtUserId, user.PassporId.ToString()));
            claims.Add(new Claim(JwtUserName, user.UserCode));
            claims.Add(new Claim(JwtOpenId, user.OpenId));

            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: ISSUER,
                audience: AUDIENCE,
                claims: claims,
                expires: DateTime.Now.AddHours(tokenTimestamp),
                signingCredentials: creds);

            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return(token);
        }