예제 #1
0
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static JwtTokenModel SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();

            if (!jwtHandler.CanReadToken(jwtStr))
            {
                return(null);
            }
            string           iss      = JwtConfig.Config.Issuer;
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);

            if (jwtToken.Issuer != iss)
            {
                return(null);
            }
            if (jwtToken.ValidTo.ToLocalTime() < DateTime.Now)
            {
                return(null);
            }

            jwtToken.Payload.TryGetValue(ClaimTypes.Role, out var role);
            jwtToken.Payload.TryGetValue("Name", out var name);
            jwtToken.Payload.TryGetValue("Code", out var code);

            var tm = new JwtTokenModel
            {
                Uid  = jwtToken.Id.ToString(),
                Role = role?.ToString(),
                Code = code?.ToString(),
                Name = name?.ToString()
            };

            return(tm);
        }
예제 #2
0
        /// <summary>
        /// 创建AccessToken
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <returns></returns>
        public static Token CreateAccessToken(JwtTokenModel tokenModel)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                new Claim("Code", tokenModel.Code),
                new Claim("Name", tokenModel.Name),
            };

            // 可以将一个用户的多个角色全部赋予;
            claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));

            return(CreateToken(claims));
        }