Poszukiwacz/Serwer/Serwer.Infrastructure/Services/JwtHandler.cs

56 lines
1.8 KiB
C#
Raw Permalink Normal View History

2020-12-06 18:31:05 +01:00
using Microsoft.IdentityModel.Tokens;
using Serwer.Infrastructure.DTO;
using Serwer.Infrastructure.Extentions;
using Serwer.Infrastructure.Settings;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
namespace Serwer.Infrastructure.Services
{
public class JwtHandler: IJwtHandler
{
private readonly JwtSettings _settings;
public JwtHandler(JwtSettings settings)
{
_settings = settings;
}
public JwtDto CreateToken(Guid userId)
{
var now = DateTime.UtcNow;
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Sub, userId.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName, userId.ToString()),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, now.ToTimestamp().ToString(), ClaimValueTypes.Integer64)
};
var expires = now.AddMinutes(_settings.ExpiryMinutes);
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Key)),
SecurityAlgorithms.HmacSha256);
var jwt = new JwtSecurityToken(
issuer: _settings.Issuer,
claims: claims,
notBefore: now,
expires: expires,
signingCredentials: signingCredentials
);
var token = new JwtSecurityTokenHandler().WriteToken(jwt);
return new JwtDto
{
UserId = userId,
Token = token,
Expires = expires.ToTimestamp()
};
}
}
}