Add JWT authentication with AuthController and services

This commit is contained in:
Denis Urs Rudolph
2026-04-03 21:00:16 +02:00
parent 8bfd49e0ab
commit b6962e1024
6 changed files with 224 additions and 12 deletions
+29
View File
@@ -1,5 +1,9 @@
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using RacePlannerApi.Data;
using RacePlannerApi.Services;
var builder = WebApplication.CreateBuilder(args);
@@ -8,6 +12,29 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApi();
// Configure JWT Authentication
var jwtKey = builder.Configuration["Jwt:Key"] ?? "your-secret-key-here-minimum-32-characters-long";
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "RacePlannerApi";
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "RacePlannerClient";
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtIssuer,
ValidAudience = jwtAudience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
// Register services
builder.Services.AddScoped<JwtTokenService>();
// Configure Entity Framework Core with PostgreSQL
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
?? "Host=localhost;Database=RacePlanner;Username=postgres;Password=postgres";
@@ -40,6 +67,8 @@ app.UseHttpsRedirection();
// Apply CORS
app.UseCors("AllowFrontend");
// Authentication & Authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();