1 Commits

Author SHA1 Message Date
dffd31cd0f 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
2025-05-27 12:20:23 +02:00
5 changed files with 73 additions and 55 deletions

View File

@ -6,12 +6,21 @@ using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
using USEntryCoach.Server.Services;
using USEntryCoach.Server.Settings;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var apiSettingsSection = builder.Configuration.GetSection(ApiSettings.SectionName);
var authSettingsSection = builder.Configuration.GetSection(AuthenticationSettings.SectionName);
builder.Services.AddOptionsWithValidateOnStart<ApiSettings>().Bind(apiSettingsSection).ValidateDataAnnotations();
builder.Services.AddOptionsWithValidateOnStart<AuthenticationSettings>().Bind(authSettingsSection).ValidateDataAnnotations();
ApiSettings? apiSettings = apiSettingsSection.Get<ApiSettings>();
AuthenticationSettings? authSettings = authSettingsSection.Get<AuthenticationSettings>();
builder.Services.AddSingleton<TokenService>();
// Configure JWT token generation.
@ -21,28 +30,14 @@ builder.Services.AddAuthentication(config =>
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
// TODO: Use Microsoft.Extensions.Options?
// var myOptions = new MyOptions(); // Your settings class
// builder.Configuration.GetSection("MySection").Bind(myOptions);
// myOptions now has the values
//
// TODO: This is identical in TokenService
string? secretToken = builder.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.");
}
byte[] secretKey = Encoding.ASCII.GetBytes(secretToken);
// TODO: Only for debug!
config.RequireHttpsMetadata = false;
config.SaveToken = true;
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secretKey),
IssuerSigningKey = new SymmetricSecurityKey(authSettings!.JwtGenerationSecretBytes),
ValidateIssuer = false,
ValidateAudience = false
};
@ -75,9 +70,9 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
HttpClient client = new();
string? apiKey = app.Configuration.GetValue<string>("API:OpenAI");
//string? apiKey = app.Configuration.GetValue<string>("API:OpenAI");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiSettings.OpenAiToken}");
app.MapPost("/login", Login);
@ -131,8 +126,8 @@ app.MapGet("/user", (ClaimsPrincipal user) =>
app.MapGet("/ephemeral_token", async () =>
{
if (apiKey == null)
throw new Exception("API key not set");
//if (apiKey == null)
// throw new Exception("API key not set");
var options = new
{

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);

View File

@ -0,0 +1,42 @@
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Microsoft.Extensions.Options;
namespace USEntryCoach.Server.Settings;
public sealed class ApiSettings
{
public const string SectionName = "API";
[Required(ErrorMessage = "OpenAI API token is required!", AllowEmptyStrings = false)]
public required string OpenAiToken { get; set; }
}
public sealed class AuthenticationSettings
{
public const string SectionName = "Authentication";
private string _jwtGenerationSecret = null!;
[Required(ErrorMessage = "JWT generation secret token is required!", AllowEmptyStrings = false)]
public required string JwtGenerationSecret
{
get => _jwtGenerationSecret;
set
{
_jwtGenerationSecret = value;
JwtGenerationSecretBytes = Encoding.UTF8.GetBytes(value);
}
}
public byte[] JwtGenerationSecretBytes { get; private set; }
const string JwtExpiryTimeMin = "00:00:30";
const string JwtExpiryTimeMax = "24:00:00";
[Range(typeof(TimeSpan), JwtExpiryTimeMin, JwtExpiryTimeMax,
ErrorMessage = $"JWT expiry time must be in the range from {JwtExpiryTimeMin} to {JwtExpiryTimeMax}.")]
public TimeSpan JwtExpiryTime { get; set; } = TimeSpan.FromMinutes(5);
}

View File

@ -6,9 +6,9 @@
}
},
"API": {
"OpenAI": "Please set the key in secrets.json! NEVER HERE!!!"
"OpenAiToken": "Please set the key in secrets.json! NEVER HERE!!!"
},
"Authentication": {
"Secret": "Please provide a GUID (without dashes) as secret."
"JwtGenerationSecret": "Please provide a GUID (without dashes) as secret."
}
}

View File

@ -7,6 +7,10 @@
},
"AllowedHosts": "*",
"API": {
"OpenAI": "[NO_API_KEY]"
"OpenAiToken": "[NO_API_KEY]"
},
"Authentication": {
"JwtGenerationSecret": "Please provide a GUID (without dashes) as secret.",
"JwtExpiryTime": "00:15:00"
}
}