61 lines
1.7 KiB
C#
61 lines
1.7 KiB
C#
using Metrolog_API.Models;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
|
|
namespace Metrolog_API.Services
|
|
{
|
|
public class JWTService
|
|
{
|
|
private RoleService _RoleService;
|
|
|
|
private string _JwtSecret;
|
|
private int _JwtExpirationMinutes;
|
|
|
|
public JWTService(RoleService roleService)
|
|
{
|
|
_RoleService = roleService;
|
|
|
|
_JwtSecret = System.Environment.GetEnvironmentVariable("JWT_SECRET");
|
|
_JwtExpirationMinutes = int.Parse(System.Environment.GetEnvironmentVariable("JWT_EXPIRATION_MINUTES"));
|
|
}
|
|
public async Task<string> GenerateUserJwtToken(UserModel user)
|
|
{
|
|
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
|
|
byte[] key = Encoding.ASCII.GetBytes(_JwtSecret);
|
|
|
|
List<Claim> claims = new List<Claim>
|
|
{
|
|
new Claim(ClaimTypes.Email, user.Email),
|
|
new Claim(ClaimTypes.Name, $"{user.TitlesFrontName} {user.Name} {user.Surname} {user.TitlesBehindName}")
|
|
};
|
|
|
|
// Add permissions to JWT
|
|
foreach (string roleName in user.Roles)
|
|
{
|
|
RoleModel? role = await _RoleService.GetByNameAsync(roleName);
|
|
if (role != null)
|
|
{
|
|
foreach (string permission in role.Permissions)
|
|
{
|
|
if (claims.Find(x => x.Value == permission) == null)
|
|
{
|
|
claims.Add(new Claim("permission", permission));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Subject = new ClaimsIdentity(claims),
|
|
Expires = DateTime.UtcNow.AddMinutes(2),
|
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
|
};
|
|
|
|
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
}
|
|
}
|