Standardize API auth challenge responses as ProblemDetails

This commit is contained in:
2026-02-07 01:51:09 +01:00
parent 567502d665
commit b16bf8007f
3 changed files with 30 additions and 26 deletions

View File

@@ -2,6 +2,7 @@ using GameList.Data;
using GameList.Endpoints;
using GameList.Infrastructure;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Data.Sqlite;
@@ -54,16 +55,8 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
options.ExpireTimeSpan = TimeSpan.FromDays(30);
options.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
},
OnRedirectToAccessDenied = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
}
OnRedirectToLogin = ctx => WriteUnauthorizedChallengeAsync(ctx.HttpContext),
OnRedirectToAccessDenied = ctx => WriteUnauthorizedChallengeAsync(ctx.HttpContext)
};
});
@@ -139,6 +132,26 @@ static ForwardedHeadersOptions BuildForwardedHeadersOptions(IConfiguration confi
return options;
}
static Task WriteUnauthorizedChallengeAsync(HttpContext context)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
if (!context.Request.Path.StartsWithSegments("/api"))
return Task.CompletedTask;
if (context.Response.HasStarted)
return Task.CompletedTask;
context.Response.ContentType = "application/problem+json";
var problem = new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Unauthorized",
Detail = "Unauthorized"
};
problem.Extensions["error"] = "Unauthorized";
return context.Response.WriteAsJsonAsync(problem);
}
static void UpdateIndexMetaBase(IWebHostEnvironment env, string basePath)
{
try