username@email.com
2025-02-05 d86bc04d0b34f2b7d9ddbd30ee703b51d48876e8
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
using Furion.Authorization;
using Furion.DataEncryption;
using Furion;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using EzCoreNet.Redis;
 
using SqlSugar.Extensions;
 
using Furion.FriendlyException;
 
namespace cylsg.Authorization
{
    /// <summary>
    /// 
    /// </summary>
    public class EzAuthorizationService : IEzAuthorizationService, IScoped
    {
        private IEzCoreNetRedisService _redisCacheSc;
        private IHttpContextAccessor _Context;
        public EzAuthorizationService(IEzCoreNetRedisService redisCacheSc, IHttpContextAccessor httpContext)
        {
            _redisCacheSc = redisCacheSc;
            _Context = httpContext;
        }
        /// <summary>
        /// Token 
        /// </summary>
        /// <returns></returns>
        public TokenInfo CreateToken<T>(T jwt) where T : EzJwtModel
        {
 
            IDictionary<string, object> propertyDictionary = new Dictionary<string, object>();
 
            PropertyInfo[] properties = jwt.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
            foreach (PropertyInfo property in properties)
            {
                string propertyName = property.Name;
                object propertyValue = property.GetValue(jwt);
 
                propertyDictionary.Add(propertyName.ToLower(), propertyValue);
            }
            var expires = DateTime.Now.AddSeconds(Convert.ToInt32(App.GetConfig<JWTSettingsOptions>("JWTSettings").ExpiredTime * 60 ?? 3600));
            var token = JWTEncryption.Encrypt(propertyDictionary, App.GetConfig<JWTSettingsOptions>("JWTSettings").ExpiredTime ?? 3600);
 
            DateTimeOffset dto = new DateTimeOffset(DateTime.Now);
            var Expires = dto.ToUnixTimeSeconds();
            IDictionary<string, object> REfpropertyDictionary = new Dictionary<string, object>();
            REfpropertyDictionary.Add(new(
                       "RefTokenID", $"{jwt.ITCode}:{Expires}"
                    ));
 
            var RefExpires = App.Configuration["JWTSettings:RefreshTokenExpires"].ObjToInt();
 
            var refreshToken = JWTEncryption.Encrypt(REfpropertyDictionary, RefExpires);
 
            //写入刷新可Token时间
            _redisCacheSc.Add($"{jwt.ITCode}:{Expires}", jwt, RefExpires * 60);
 
            return new TokenInfo
            {
                accessToken = token,
                expires = expires,
                refreshToken = refreshToken
            };
 
        }
        /// <summary>
        /// 刷新TOKEN
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="refToken"></param>
        /// <returns></returns>
        /// <exception cref="TAxiosException"></exception>
        public async Task<TokenInfo?> RefreshToken<T>(string refToken) where T : EzJwtModel
        {
            // IDictionary<string, object> REfpropertyDictionary = new Dictionary<string, object>();
 
            //  var tokenInfo = JWTEncryption.ReadJwtToken("token");
            var (isValid, tokenData, validationResult) = JWTEncryption.Validate(refToken);
            if (!isValid)
                new EZCoreException(" 系统错误,请重新登录", System.Net.HttpStatusCode.Unauthorized);
            var user = tokenData.Claims;
            if (user == null)
                throw new EZCoreException("参数丢失,请重新登录", System.Net.HttpStatusCode.Unauthorized);
 
            var key = user.Where(x => x.Type == "RefTokenID").Select(x => x.Value).FirstOrDefault();
            //if (key == null)
            //    throw Oops.Oh("token已过期,请重新登录", System.Net.HttpStatusCode.Unauthorized);
            var jwtConfig = App.GetConfig<JWTSettingsOptions>("JWTSettings");
            if (jwtConfig == null)
                throw new EZCoreException(" 系统错误,请重新登录", System.Net.HttpStatusCode.Unauthorized);
            var LoinData = _redisCacheSc.Get<T>(key);
            if (LoinData == null)
 
                throw new EZCoreException("token已过期,请重新登录", System.Net.HttpStatusCode.Unauthorized); //Oops.Oh("token已过期,请重新登录", System.Net.HttpStatusCode.Unauthorized);
            var refreshTokenouttimes = _redisCacheSc.GetTtl(key);
            if (refreshTokenouttimes <= 0)
            {
 
                throw new EZCoreException("token已过期,请重新登录", System.Net.HttpStatusCode.Unauthorized);
            }
            return await Task.Run<TokenInfo?>(() =>
            {
 
 
 
                IDictionary<string, object> propertyDictionary = new Dictionary<string, object>();
 
                PropertyInfo[] properties = LoinData.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
                foreach (PropertyInfo property in properties)
                {
                    string propertyName = property.Name;
                    object propertyValue = property.GetValue(LoinData);
 
                    propertyDictionary.Add(propertyName.ToLower(), propertyValue);
                }
 
 
                var expires = DateTime.Now.AddSeconds(Convert.ToInt32(jwtConfig.ExpiredTime * 60));
 
                var token = JWTEncryption.Encrypt(propertyDictionary, jwtConfig.ExpiredTime);
 
 
                IDictionary<string, object> refreshTokenClaims = new Dictionary<string, object>();
 
 
                refreshTokenClaims.Add(new(
                           "RefTokenID", key
                        ));
 
                var refreshToken = JWTEncryption.Encrypt(refreshTokenClaims, refreshTokenouttimes);
 
                return new TokenInfo
                {
                    accessToken = token,
                    expires = expires,
                    refreshToken = refreshToken
                };
            });
 
 
 
        }
    }
}