using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using Microsoft.IdentityModel.Tokens; namespace WebAPI.Utility { public static class JWTHelper { static JWTHelper() { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); } // 秘钥 private const string SecretKey = "8sK2pR9vFg5tHjNm7qWaEe4dUcxZbL$S6y"; private static readonly SymmetricSecurityKey _securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey)); // 签发 Token public static string GenerateToken(string userId, string userName, string HCampanyName= "zjzyms") { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var credentials = new SigningCredentials(_securityKey, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "zjzyms", audience: HCampanyName, claims: claims, expires: DateTime.UtcNow.AddHours(2), // 两小时过期时间 signingCredentials: credentials ); return new JwtSecurityTokenHandler().WriteToken(token); } // 验证 Token 并返回 ClaimsPrincipal public static ClaimsPrincipal ValidateToken(string token, string HCampanyName= "zjzyms") { var handler = new JwtSecurityTokenHandler(); var parameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "zjzyms", ValidateAudience = true, ValidAudience = HCampanyName, ValidateIssuerSigningKey = true, IssuerSigningKey = _securityKey, ValidateLifetime = true, ClockSkew = TimeSpan.Zero, // 不允许时间误差 }; try { var principal = handler.ValidateToken(token, parameters, out var validatedToken); return principal; } catch { return null; } } // 刷新Token public static string refreshToken(string token) { var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token); var czybm = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value; var zymm = jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value; // 通过上一个token的值刷新token return GenerateToken(czybm, zymm); } // 判断Token 是否即将过期 public static bool TokenAboutToExpire(string token) { var jwt = new JwtSecurityTokenHandler().ReadJwtToken(token); var validTo = jwt.ValidTo; if(validTo.Subtract(DateTime.UtcNow).TotalMinutes < 5) { return true; } return false; } } }