2026-08-13 23:10:22 +07:00
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
2026-08-19 23:25:08 +07:00
|
|
|
using mws.backend.dotnet.application.Auth;
|
2026-08-13 23:10:22 +07:00
|
|
|
|
2026-08-19 23:25:08 +07:00
|
|
|
namespace mws.backend.dotnet.infrastructure.Authentication;
|
2026-08-13 23:10:22 +07:00
|
|
|
|
|
|
|
|
public class JwtTokenService(JwtOptions options) : ITokenService
|
|
|
|
|
{
|
|
|
|
|
public string CreateToken(Guid userId, string username)
|
|
|
|
|
{
|
|
|
|
|
var claims = new List<Claim>
|
|
|
|
|
{
|
|
|
|
|
new(JwtRegisteredClaimNames.Sub, userId.ToString()),
|
|
|
|
|
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
|
|
|
|
new(ClaimTypes.Name, username),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Secret));
|
|
|
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
|
|
|
|
|
|
|
|
var token = new JwtSecurityToken(
|
|
|
|
|
issuer: options.Issuer,
|
|
|
|
|
audience: options.Audience,
|
|
|
|
|
claims: claims,
|
|
|
|
|
expires: DateTime.UtcNow.Add(options.Expiration),
|
|
|
|
|
signingCredentials: creds);
|
|
|
|
|
|
|
|
|
|
return new JwtSecurityTokenHandler().WriteToken(token);
|
|
|
|
|
}
|
|
|
|
|
}
|