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

@ -1,13 +1,64 @@
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
using USEntryCoach.Server.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddSingleton<TokenService>();
// Configure JWT token generation.
builder.Services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
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),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(nameof(UserRole.Developer), policy => policy.RequireRole(nameof(UserRole.Developer)));
options.AddPolicy(nameof(UserRole.User), policy => policy.RequireRole(nameof(UserRole.User)));
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseDefaultFiles();
app.MapStaticAssets();
@ -24,13 +75,61 @@ string? apiKey = app.Configuration.GetValue<string>("API:OpenAI");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
app.MapPost("/login", Login);
app.MapGet("/hello", () => "Hello World!").RequireAuthorization("admin_greetings");
async Task<IResult> Login(LoginCredentials credentials, TokenService tokenService, HttpContext context)
{
// TODO: Check with database
User? user = null;
if (credentials is {Username:"developer", Password:"dev"})
{
user = new User()
{
Username = credentials.Username,
Password = credentials.Password,
Id = Guid.CreateVersion7(),
Role = UserRole.Developer
};
}
else if (credentials is {Username:"user", Password:"us"})
{
user = new User()
{
Username = credentials.Username,
Password = credentials.Password,
Id = Guid.CreateVersion7(),
Role = UserRole.User
};
}
if (user == null)
{
return Results.Unauthorized();
}
var token = tokenService.GenerateToken(user);
return Results.Ok(new { user = user, token = token });
}
app.MapGet("/developer", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization(nameof(UserRole.Developer));
app.MapGet("/user", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization(nameof(UserRole.User));
app.MapGet("/ephemeral_token", async () =>
{
if (apiKey == null)
throw new Exception("API key not set");
#pragma warning disable OPENAI002
var options = new
{
model = "gpt-4o-mini-realtime-preview",
@ -44,8 +143,6 @@ app.MapGet("/ephemeral_token", async () =>
//}//ConversationTurnDetectionOptions.CreateServerVoiceActivityTurnDetectionOptions(0.5f, TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(500), true)
};
#pragma warning restore OPENAI002
try
{
JsonContent content = JsonContent.Create(options);