2024-10-30 17:52:22 +08:00
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
2024-11-03 11:21:47 +08:00
|
|
|
|
using SiteManagementSystem_SoftwareEngineering_.Configuration;
|
2024-10-30 17:52:22 +08:00
|
|
|
|
using SiteManagementSystem_SoftwareEngineering_.Entity;
|
|
|
|
|
using SiteManagementSystem_SoftwareEngineering_.Interface;
|
|
|
|
|
|
|
|
|
|
namespace SiteManagementSystem_SoftwareEngineering_.Factory
|
|
|
|
|
{
|
|
|
|
|
public class TokenFactory(
|
|
|
|
|
TokenFactoryConfiguration configuration
|
|
|
|
|
) : ITokenFactory
|
|
|
|
|
{
|
|
|
|
|
private readonly TokenFactoryConfiguration _configuration = configuration;
|
|
|
|
|
|
|
|
|
|
private string CreateToken(IEnumerable<Claim> claims, User user, DateTime expires)
|
|
|
|
|
{
|
|
|
|
|
// 为什么把 NameIdentifier 单独写在这儿?
|
|
|
|
|
claims = claims.Append(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
|
|
|
|
|
var credentials = new SigningCredentials(
|
|
|
|
|
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.SigningKey)),
|
|
|
|
|
SecurityAlgorithms.HmacSha256
|
|
|
|
|
);
|
|
|
|
|
var token = new JwtSecurityToken(
|
|
|
|
|
issuer: _configuration.Issuer,
|
|
|
|
|
audience: _configuration.Audience,
|
|
|
|
|
notBefore: DateTime.Now,
|
|
|
|
|
expires: expires,
|
|
|
|
|
claims: claims,
|
|
|
|
|
signingCredentials: credentials
|
|
|
|
|
);
|
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string CreateAccessToken(User user)
|
|
|
|
|
{
|
|
|
|
|
var expires = DateTime.Now.AddMinutes(_configuration.AccessTokenExpire);
|
|
|
|
|
return CreateToken(
|
|
|
|
|
user.GetUserClaims().Append(new Claim("TokenType", "AccessToken")),
|
|
|
|
|
user,
|
|
|
|
|
expires
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public string CreateRefreshToken(User user)
|
|
|
|
|
{
|
|
|
|
|
var expires = DateTime.Now.AddMinutes(_configuration.RefreshTokenExpire);
|
|
|
|
|
return CreateToken([new Claim("TokenType", "RefreshToken")], user, expires);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|