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 WIDESEAWCS_Core.Const; using WIDESEAWCS_Core.Helper; using WIDESEAWCS_Core.HttpContextUser; namespace WIDESEAWCS_Core.Authorization { public class JwtHelper { /// /// 生成JWT /// /// /// public static string IssueJwt(TokenModelJwt tokenModel) { string exp = $"{new DateTimeOffset(DateTime.Now.AddMinutes(/*tokenModel.UserId == 1 ? 43200 : */AppSettings.app("ExpMinutes").ObjToInt())).ToUnixTimeSeconds()}"; List claims = new List { 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; } /// /// 解析 /// /// /// 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; } /// /// 获取过期时间 /// /// /// 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; } } } /// /// 令牌 /// public class TokenModelJwt { /// /// UserId /// public long UserId { get; set; } /// /// 角色 /// public int RoleId { get; set; } /// /// 职能 /// public string UserName { get; set; } public long TenantId { get; set; } } }