Basic login an authorize in backend

This commit is contained in:
Simon Lübeß
2025-05-22 18:25:56 +02:00
parent 5c84bbc35a
commit 3e7b04df1c
7 changed files with 187 additions and 4 deletions

View File

@ -0,0 +1,56 @@
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);
}
}