Files
Govor/Govor.Application/Services/JwtService.cs
T
2025-07-01 21:42:34 +07:00

40 lines
1.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Govor.API.Services.Authentication.Interfaces;
using Govor.Core.Models;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Govor.Application.Services;
public class JwtService : IJwtService
{
private JwtOption _jwtOption;
private IInvitesService _invitesService;
public JwtService(IOptions<JwtOption> options, IInvitesService invitesService)
{
_jwtOption = options.Value;
_invitesService = invitesService;
}
public string GenerateJwtToken(User user)
{
var claims = new[]
{
new Claim("userId", user.Id.ToString()),
new Claim(ClaimTypes.Role, _invitesService.GetRoleAsync(user).Result, ClaimValueTypes.String)
};
var singing = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOption.SecretKeу)),
SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(signingCredentials: singing,
expires: DateTime.UtcNow.AddHours(_jwtOption.Hours),
claims: claims);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}