Files
zszq-trs/YLErpDAL/Helpers/AuthHelper.cs
T
shangzhongyuan 944c0a0e0d ```
feat(auth): 添加登录Token过期时间和密码错误限制配置

- 在IErpConfig接口中新增LoginTokenExpireSeconds、PasswordErrorLimit和
  PasswordErrorLockMinutes属性
- 在ProjectSettings类中添加对应的配置项和默认值
- 在appconfig.xml中添加相关配置参数
- 修改AuthHelper类使用动态配置的Token过期时间
- 实现密码错误次数限制和账户锁定功能

```
2026-02-06 17:10:58 +08:00

98 lines
3.3 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###";
/// <summary>
/// 创建jwt令牌
/// </summary>
public static string CreateJwtToken(ClaimsIdentity identity)
{
var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecretKey));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(identity),
Expires = DateTime.UtcNow.AddSeconds(ExpireInSeconds),
Issuer = JwtIssuer,
Audience = JwtAudience,
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
public static string CreateJwtToken2(ClaimsIdentity identity)
{
var key = new SymmetricSecurityKey(Convert.FromBase64String(JwtSecretKey));
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(identity),
Expires = DateTime.UtcNow.AddSeconds(ExpireInSeconds),
IssuedAt = DateTime.Now,
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;
}
}
}