Use typesafe options
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

This commit is contained in:
Simon Lübeß
2025-05-27 12:20:23 +02:00
parent f4737f4dcf
commit dffd31cd0f
5 changed files with 73 additions and 55 deletions

View File

@ -1,39 +1,15 @@
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
public class TokenService(IOptions<AuthenticationSettings> authenticationSettings)
{
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();
@ -42,11 +18,12 @@ public class TokenService
{
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)
Expires = DateTime.UtcNow.Add(authenticationSettings.Value.JwtExpiryTime),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(authenticationSettings.Value.JwtGenerationSecretBytes),
SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);