Add JWT authentication with AuthController and services
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user