AS400_API_DOTNET/Auth/TokenService.cs
2025-10-17 16:01:56 +07:00

49 lines
1.4 KiB
C#

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AS400API.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace AS400API.Auth;
public sealed class TokenService
{
private readonly JwtOptions _options;
private readonly JwtSecurityTokenHandler _tokenHandler = new();
public TokenService(JwtOptions options)
{
_options = options;
}
public string CreateToken(DemoUser user)
{
var signingCredentials = new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key)),
SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, user.Username),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(ClaimTypes.Name, user.Username)
};
foreach (var role in user.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_options.AccessTokenLifetimeMinutes),
signingCredentials: signingCredentials);
return _tokenHandler.WriteToken(token);
}
}