Add initial implementation of API, database, and user management components.
This commit is contained in:
47
MikrocopApi/Services/JwtTokenService.cs
Normal file
47
MikrocopApi/Services/JwtTokenService.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using MikrocopApi.Configuration;
|
||||
using MikrocopDb.Entities;
|
||||
|
||||
namespace MikrocopApi.Services;
|
||||
|
||||
public sealed class JwtTokenService : IJwtTokenService
|
||||
{
|
||||
private readonly JwtOptions _options;
|
||||
|
||||
public JwtTokenService(IOptions<JwtOptions> options)
|
||||
{
|
||||
_options = options.Value;
|
||||
}
|
||||
|
||||
public (string AccessToken, DateTime ExpiresAtUtc) Generate(UserEntity user)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var expires = now.AddMinutes(_options.ExpirationMinutes);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
||||
new(JwtRegisteredClaimNames.UniqueName, user.UserName),
|
||||
new(ClaimTypes.Name, user.UserName),
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString())
|
||||
};
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SigningKey));
|
||||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _options.Issuer,
|
||||
audience: _options.Audience,
|
||||
claims: claims,
|
||||
notBefore: now,
|
||||
expires: expires,
|
||||
signingCredentials: creds);
|
||||
|
||||
var serialized = new JwtSecurityTokenHandler().WriteToken(token);
|
||||
return (serialized, expires);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user