add(refreshTokenService):完善刷新令牌服务
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
using IM_API.Interface.Services;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace IM_API.Services
|
||||
{
|
||||
public class JWTService : IJWTService
|
||||
{
|
||||
private readonly IConfiguration _config;
|
||||
private readonly string _key;
|
||||
private readonly string _issuer;
|
||||
private readonly string _audience;
|
||||
private readonly int _accessMinutes;
|
||||
|
||||
public JWTService(IConfiguration config)
|
||||
{
|
||||
_config = config;
|
||||
_key = _config["Jwt:Key"]!;
|
||||
_issuer = _config["Jwt:Issuer"]!;
|
||||
_audience = _config["Jwt:Audience"]!;
|
||||
_accessMinutes = int.Parse(_config["Jwt:AccessTokenMinutes"] ?? "15");
|
||||
}
|
||||
|
||||
public string GenerateAccessToken(IEnumerable<Claim> claims, DateTime expiresAt)
|
||||
{
|
||||
var keyBytes = Encoding.UTF8.GetBytes(_key);
|
||||
var creds = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _issuer,
|
||||
audience: _audience,
|
||||
claims: claims,
|
||||
expires: expiresAt,
|
||||
signingCredentials: creds
|
||||
);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
public (string token, DateTime expiresAt) CreateAccessTokenForUser(int userId, string username, string role)
|
||||
{
|
||||
var expiresAt = DateTime.UtcNow.AddMinutes(_accessMinutes);
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
|
||||
new Claim(ClaimTypes.Name, username),
|
||||
new Claim(ClaimTypes.Role, role)
|
||||
};
|
||||
var token = GenerateAccessToken(claims, expiresAt);
|
||||
return (token, expiresAt);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user