hutongqing
2024-11-20 0845150c79d1ebd664753931933e786ed8bd06c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Const;
using WIDESEA_Core.Helper;
using WIDESEA_Core.HttpContextUser;
 
namespace WIDESEA_Core.Authorization
{
    public class JwtHelper
    {
 
        /// <summary>
        /// 生成JWT
        /// </summary>
        /// <param name="serInfo"></param>
        /// <returns></returns>
        public static string IssueJwt(TokenModelJwt tokenModel)
        {
            string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(/*tokenModel.UserId == 1 ? 43200 : */AppSettings.app("ExpMinutes").ObjToInt())).ToUnixTimeSeconds()}";
            List<Claim> claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Jti, tokenModel.UserId.ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat,  $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                    new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    //JWT过期时间
                    //默认设置jwt过期时间120分钟
                    new Claim (JwtRegisteredClaimNames.Exp, exp),
                    new Claim(JwtRegisteredClaimNames.Iss, AppSecret.Issuer),
                    new Claim(JwtRegisteredClaimNames.Aud, AppSecret.Audience),
                    new Claim(ClaimTypes.Role, tokenModel.RoleId.ToString()),
                    new Claim(ClaimTypes.Name, tokenModel.UserName),
                    new Claim(nameof(TokenModelJwt.TenantId), tokenModel.TenantId.ToString())
               };
 
            // 可以将一个用户的多个角色全部赋予;
            // 作者:DX 提供技术支持;
            //秘钥16位
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSecret.JWT));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            JwtSecurityToken securityToken = new JwtSecurityToken(issuer: AppSecret.Issuer, claims: claims, signingCredentials: creds);
            string jwt = new JwtSecurityTokenHandler().WriteToken(securityToken);
            return jwt;
        }
 
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static UserInfo SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            UserInfo userInfo = new UserInfo
            {
                UserId = Convert.ToInt32(jwtToken.Id),
                RoleId = (jwtToken.Payload[ClaimTypes.Role] ?? 0).ObjToInt(),
            };
            return userInfo;
        }
        /// <summary>
        /// 获取过期时间
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static DateTime GetExp(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
 
            DateTime expDate = (jwtToken.Payload[JwtRegisteredClaimNames.Exp] ?? 0).ObjToInt().GetTimeSpmpToDate();
            return expDate;
        }
        public static bool IsExp(string jwtStr)
        {
            return GetExp(jwtStr) < DateTime.Now;
        }
 
        public static int GetUserId(string jwtStr)
        {
            try
            {
                if (jwtStr.IsNullOrEmpty()) return 0;
                jwtStr = jwtStr.Replace("Bearer ", "");
                return new JwtSecurityTokenHandler().ReadJwtToken(jwtStr).Id.ObjToInt();
            }
            catch
            {
                return 0;
            }
        }
    }
 
    /// <summary>
    /// 令牌
    /// </summary>
    public class TokenModelJwt
    {
        /// <summary>
        /// UserId
        /// </summary>
        public long UserId { get; set; }
        /// <summary>
        /// 角色
        /// </summary>
        public int RoleId { get; set; }
        /// <summary>
        /// 职能
        /// </summary>
        public string UserName { get; set; }
 
        public long TenantId { get; set; }
 
    }
}