41 lines
1.1 KiB
C#
41 lines
1.1 KiB
C#
|
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
|
|||
|
{
|
|||
|
// TODO: Переместить ключ и время в надежное место
|
|||
|
private const string _key = "secretkey_secretkey_secretkey_secretkey";
|
|||
|
|
|||
|
private const int _expiresHours = 24;
|
|||
|
|
|||
|
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;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|