Files
US-Entry-Coach/USEntryCoach.Server/Services/TokenService.cs
2025-05-22 18:26:09 +02:00

56 lines
1.9 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
namespace USEntryCoach.Server.Services;
public class TokenService
{
private byte[] _secretToken;
private double _jwtExpiryMinutes;
private const double DefaultJwtExpiryMinutes = 15;
public TokenService(IConfiguration configuration)
{
string? secretToken = configuration.GetValue<string>("Authentication:Secret");
if (secretToken == null)
{
throw new Exception("No Authentication Secret Token set! Please define a value for \"Authentication:SecretToken\" in appsettings.json.");
}
_secretToken = Encoding.ASCII.GetBytes(secretToken);
double? jwtExpiryMinutes = configuration.GetValue<double?>("Authentication:JwtExpiryMinutes");
if (jwtExpiryMinutes == null)
{
// TODO: Use logger
Console.WriteLine($"Warning: No expiry time for jwt session tokens defined. Using {DefaultJwtExpiryMinutes} minutes.");
}
_jwtExpiryMinutes = jwtExpiryMinutes ?? DefaultJwtExpiryMinutes;
}
public string GenerateToken(User user)
{
JwtSecurityTokenHandler tokenHandler = new();
SecurityTokenDescriptor tokenDescriptor = new()
{
Subject = new ClaimsIdentity([
new Claim(ClaimTypes.Name, user.Username),
//new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role.ToString())
]),
Expires = DateTime.UtcNow.AddMinutes(_jwtExpiryMinutes),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_secretToken), SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}