PIAPS_CW/BusinessLogic/Tools/JwtProvider.cs

46 lines
1.1 KiB
C#
Raw Permalink Normal View History

2024-06-13 18:41:59 +04:00
using Contracts.BindingModels;
using Contracts.ViewModels;
using Microsoft.IdentityModel.Tokens;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic.Tools
{
public class JwtProvider
{
2024-06-15 00:01:39 +04:00
private static string _key;
2024-06-13 18:41:59 +04:00
2024-06-15 00:01:39 +04:00
private static int _expiresHours;
2024-06-13 18:41:59 +04:00
public static string Generate(UserBindingModel user)
{
var signingCredentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key)),
SecurityAlgorithms.HmacSha256);
Claim[] claims = [
new("userId", user.Id.ToString()),
new("role", user.Role.Name)
];
var token = new JwtSecurityToken(signingCredentials: signingCredentials,
expires: DateTime.UtcNow.AddHours(_expiresHours),
claims: claims);
var stringToken = new JwtSecurityTokenHandler().WriteToken(token);
return stringToken;
}
2024-06-15 00:01:39 +04:00
public void SetupJwtOptions(JwtOptions options)
{
_key = options.SecretKey;
_expiresHours = options.ExpiresHours;
}
2024-06-13 18:41:59 +04:00
}
}