72 lines
2.4 KiB
C#
72 lines
2.4 KiB
C#
|
|
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;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// JWT工具类
|
||
|
|
/// </summary>
|
||
|
|
public static class JwtHelper
|
||
|
|
{
|
||
|
|
/// <summary>
|
||
|
|
/// 生成JWT令牌
|
||
|
|
/// </summary>
|
||
|
|
/// <param name="userId">用户ID</param>
|
||
|
|
/// <param name="userName">用户名</param>
|
||
|
|
/// <param name="settings">JWT配置</param>
|
||
|
|
/// <returns>JWT令牌字符串</returns>
|
||
|
|
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.AddMinutes(settings.ExpiryMinutes),
|
||
|
|
signingCredentials: credentials
|
||
|
|
);
|
||
|
|
|
||
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 验证JWT令牌
|
||
|
|
/// </summary>
|
||
|
|
/// <param name="token">JWT令牌</param>
|
||
|
|
/// <param name="settings">JWT配置</param>
|
||
|
|
/// <returns>ClaimsPrincipal对象</returns>
|
||
|
|
public static ClaimsPrincipal ValidateToken(string token, JwtSettings settings)
|
||
|
|
{
|
||
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||
|
|
var key = Encoding.UTF8.GetBytes(settings.SecretKey!);
|
||
|
|
|
||
|
|
var validationParameters = new TokenValidationParameters
|
||
|
|
{
|
||
|
|
ValidateIssuer = true,
|
||
|
|
ValidIssuer = settings.Issuer,
|
||
|
|
ValidateAudience = true,
|
||
|
|
ValidAudience = settings.Audience,
|
||
|
|
ValidateIssuerSigningKey = true,
|
||
|
|
IssuerSigningKey = new SymmetricSecurityKey(key),
|
||
|
|
ValidateLifetime = true,
|
||
|
|
ClockSkew = TimeSpan.Zero
|
||
|
|
};
|
||
|
|
|
||
|
|
return tokenHandler.ValidateToken(token, validationParameters, out _);
|
||
|
|
}
|
||
|
|
}
|