56 lines
1.9 KiB
C#
56 lines
1.9 KiB
C#
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);
|
|
}
|
|
}
|
|
}
|