Last active
August 26, 2024 08:39
-
-
Save dj-nitehawk/9654ae91808df04abcfd8ec21b373a7b to your computer and use it in GitHub Desktop.
Sending custom response on JWT Bearer Auth failure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bld = WebApplication.CreateBuilder(args); | |
bld.Services | |
.AddAuthenticationJwtBearer( | |
s => s.SigningKey = "...", | |
o => | |
{ | |
o.Events = new() | |
{ | |
OnChallenge = | |
async ctx => | |
{ | |
ctx.HandleResponse(); | |
var requiresAuth = ctx.HttpContext.GetEndpoint()?.Metadata.OfType<IAuthorizeData>().Any(); | |
if (ctx.AuthenticateFailure is not null || requiresAuth is true) | |
await ctx.Response.SendErrorsAsync([new("Security", "You are unauthorized!")], 401); | |
} | |
}; | |
}) | |
.AddAuthorization() | |
.AddFastEndpoints() | |
.SwaggerDocument(); | |
var app = bld.Build(); | |
app.UseAuthentication() | |
.UseAuthorization() | |
.UseFastEndpoints( | |
c => | |
{ | |
c.Errors.UseProblemDetails(); | |
c.Endpoints.Configurator = | |
ep => | |
{ | |
if (ep.AnonymousVerbs is null) | |
ep.Description(b => b.Produces<ProblemDetails>(401)); | |
}; | |
}) | |
.UseSwaggerGen(); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment