using DocumentServiceAPI.Model; using DocumentServiceAPI.Services.IService; using Furion.Authorization; using Furion.DistributedIDGenerator; using Furion.JsonSerialization; using NetTaste; using SqlSugar.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace DocumentServiceAPI.Application.UserAndLogin.Services { /// /// token服务类 /// public class TokenService: IScoped { /// /// Token是啥 /// static string TokenKeys = "TokenKeys:"; private ISqlSugarClient _db; private UserService _UserService; private IRedisCacheService _RedisCase; public TokenService(ISqlSugarClient db, UserService UserInfoService, IRedisCacheService RedisCase ) { _db = db; _UserService = UserInfoService; _RedisCase = RedisCase; } /// /// 新建一个TOken /// /// public string CreateToken(JwtInfo jwt) { string TokenKey=TokenKeys+ getTokenKey(jwt); IDictionary propertyDictionary = new Dictionary(); 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 ID = IDGen.NextID(); jwt.JID = ID; var token= JWTEncryption.Encrypt(propertyDictionary, App.GetConfig("JWTSettings").ExpiredTime ?? 3600); if(jwt.LogInSource==LogInFrom.PC) _RedisCase.Add(TokenKey, ID.ToString(), expireSeconds: (int )(App.GetConfig("JWTSettings").ExpiredTime??3600)); return token; } /// /// 校验jwt信息是否有效,判决单端登录验证 /// /// public bool CheckToken() { var Jwtinfo= _UserService.GetJwtInfo(); var Key= getTokenKey(Jwtinfo); string T = _RedisCase.Get(Key); if (T == null) return true; if (T != Jwtinfo.JID.ToString()) return false; return true; } /// /// 获取TokenKey /// /// /// private string getTokenKey(JwtInfo jwt) { string TokenKey = TokenKeys + jwt.EID?.ToString() + jwt.UID?.ToString() + jwt.TEID?.ToString(); return TokenKey; } } }