48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace Distribution.Infra.Authorization;
|
|
|
|
public class JwtTokenService : IJwtTokenService
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public JwtTokenService(IConfiguration configuration)
|
|
{
|
|
_configuration = configuration;
|
|
}
|
|
|
|
public string GenerateToken(Models.User user)
|
|
{
|
|
var jwtSection = _configuration.GetSection("Jwt");
|
|
var key = jwtSection["Key"] ?? throw new InvalidOperationException("Jwt:Key is not configured.");
|
|
var issuer = jwtSection["Issuer"];
|
|
var audience = jwtSection["Audience"];
|
|
var expiryMinutes = int.TryParse(jwtSection["ExpiryMinutes"], out var m) ? m : 120;
|
|
|
|
var claims = new List<Claim>
|
|
{
|
|
new("sub", user.Id.ToString()),
|
|
new("username", user.Username),
|
|
new("role", user.Role?.Name ?? string.Empty),
|
|
new("role_id", user.FK_RoleId.ToString()),
|
|
new("role_level", (user.Role?.Level ?? 0).ToString())
|
|
};
|
|
|
|
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
|
|
var credentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: issuer,
|
|
audience: audience,
|
|
claims: claims,
|
|
expires: DateTime.Now.AddMinutes(expiryMinutes),
|
|
signingCredentials: credentials);
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
}
|
|
}
|