using Microsoft.IdentityModel.Tokens; using QYZH.InteractiveMagazine.Models.Settings; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace QYZH.InteractiveMagazine.Infrastructure.Auth; /// /// JWT工具类 /// public static class JwtHelper { /// /// 生成JWT令牌 /// /// 用户ID /// 用户名 /// JWT配置 /// JWT令牌字符串 public static string GenerateToken(long userId, string userName, JwtSettings settings) { var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()), new Claim(JwtRegisteredClaimNames.Name, userName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, userId.ToString()), new Claim(ClaimTypes.Name, userName) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.SecretKey!)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: settings.Issuer, audience: settings.Audience, claims: claims, expires: DateTime.Now.AddDays(settings.JwtTokenExpiryDays), signingCredentials: credentials ); return new JwtSecurityTokenHandler().WriteToken(token); } /// /// 获取Token过期时间 /// /// JWT令牌 /// 过期时间 public static DateTime? GetTokenExpiry(string token) { var tokenHandler = new JwtSecurityTokenHandler(); if (tokenHandler.ReadToken(token) is JwtSecurityToken jwtToken) { return jwtToken.ValidTo; } return null; } /// /// 从Token中获取用户ID /// /// JWT令牌 /// 用户ID public static long? GetUserIdFromToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); if (tokenHandler.ReadToken(token) is JwtSecurityToken jwtToken) { var userIdClaim = jwtToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (long.TryParse(userIdClaim?.Value, out long userId)) { return userId; } } return null; } /// /// 从Token中获取用户名 /// /// JWT令牌 /// 用户名 public static string GetUserNameFromToken(string token) { var tokenHandler = new JwtSecurityTokenHandler(); if (tokenHandler.ReadToken(token) is JwtSecurityToken jwtToken) { return jwtToken.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value ?? string.Empty; } return string.Empty; } }