Files
US-Entry-Coach/USEntryCoach.Server/Services/TokenService.cs
Simon Lübeß dffd31cd0f
All checks were successful
Build Backend and Frontend / Build & Test .NET Backend (push) Successful in 33s
Build Backend and Frontend / Build Frontend (push) Successful in 12s
Use typesafe options
2025-05-27 12:20:23 +02:00

33 lines
1.1 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
using USEntryCoach.Server.Settings;
namespace USEntryCoach.Server.Services;
public class TokenService(IOptions<AuthenticationSettings> authenticationSettings)
{
public string GenerateToken(User user)
{
JwtSecurityTokenHandler tokenHandler = new();
SecurityTokenDescriptor tokenDescriptor = new()
{
Subject = new ClaimsIdentity([
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Role, user.Role.ToString())
]),
Expires = DateTime.UtcNow.Add(authenticationSettings.Value.JwtExpiryTime),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(authenticationSettings.Value.JwtGenerationSecretBytes),
SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}