Use typesafe options
This commit is contained in:
@ -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);
|
||||
|
||||
Reference in New Issue
Block a user