AssetManager.API/AssetManager.Services/Services/JwtService.cs

54 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AssetManager.Services.Services;
public class JwtService
{
private readonly string _secretKey;
private readonly string _issuer;
private readonly string _audience;
public JwtService()
{
// 完全从环境变量读取
_secretKey = Environment.GetEnvironmentVariable("Jwt__SecretKey")
?? "your-strong-secret-key-here-2026";
_issuer = Environment.GetEnvironmentVariable("Jwt__Issuer")
?? "AssetManager";
_audience = Environment.GetEnvironmentVariable("Jwt__Audience")
?? "AssetManager";
}
public string GenerateToken(string userId, string userName, string email)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, userId ?? ""),
new Claim(JwtRegisteredClaimNames.Email, email ?? ""),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
// 如果userName不为null添加到claims中
if (!string.IsNullOrEmpty(userName))
{
claims.Add(new Claim(JwtRegisteredClaimNames.Name, userName));
}
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_secretKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _issuer,
audience: _audience,
claims: claims,
expires: DateTime.Now.AddHours(24),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}