- 移除CreateJwtToken2方法,统一使用CreateJwtToken方法 - 修改密钥处理方式,从ASCII字符串改为Base64解码 - 删除IssuedAt声明以简化令牌结构 - 更新所有相关调用点使用统一的令牌创建方法
82 lines
2.7 KiB
C#
82 lines
2.7 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Net.Http;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using YLErp;
|
|
|
|
namespace YLErp.Helpers
|
|
{
|
|
/// <summary>
|
|
/// 用户认证帮助类
|
|
/// </summary>
|
|
public class AuthHelper
|
|
{
|
|
public const string CookieAuthType = "yc_identity";
|
|
|
|
public const string JwtAuthType = "yc_mapi";
|
|
|
|
/// <summary>
|
|
/// 登录Token过期时间(秒)
|
|
/// </summary>
|
|
public static int ExpireInSeconds => PS.Config?.ErpElement?.LoginTokenExpireSeconds ?? 3600 * 10; // 默认10小时
|
|
|
|
public const string JwtIssuer = "yilian";
|
|
|
|
public const string JwtAudience = "yilian";
|
|
|
|
public const string JwtSecretKey = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrkzI1NiJ9eyJjbGFTT";
|
|
|
|
public const string JwtUserToken = "###jwt###";
|
|
|
|
public static string CreateJwtToken(ClaimsIdentity identity)
|
|
{
|
|
var key = new SymmetricSecurityKey(Convert.FromBase64String(JwtSecretKey));
|
|
|
|
var claims = new ClaimsIdentity(identity);
|
|
if (!claims.HasClaim(c => c.Type == "jti"))
|
|
{
|
|
claims.AddClaim(new Claim("jti", Guid.NewGuid().ToString("N")));
|
|
}
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = claims,
|
|
Expires = DateTime.UtcNow.AddSeconds(ExpireInSeconds),
|
|
Issuer = JwtIssuer,
|
|
Audience = JwtAudience,
|
|
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512)
|
|
};
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 解析JWT token
|
|
/// </summary>
|
|
/// <param name="token">JWT token字符串</param>
|
|
/// <returns>解析后的JWT token对象</returns>
|
|
public static JwtSecurityToken ParseJwtToken(string token)
|
|
{
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
return tokenHandler.ReadJwtToken(token);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 检查token是否需要续期
|
|
/// </summary>
|
|
/// <param name="token">JWT token对象</param>
|
|
/// <param name="thresholdSeconds">续期阈值(秒)</param>
|
|
/// <returns>是否需要续期</returns>
|
|
public static bool NeedRefreshToken(JwtSecurityToken token, int thresholdSeconds = 3600)
|
|
{
|
|
var timeUntilExpiry = token.ValidTo - DateTime.UtcNow;
|
|
return timeUntilExpiry.TotalSeconds < thresholdSeconds;
|
|
}
|
|
}
|
|
}
|