Created
June 4, 2024 04:18
-
-
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(); | |
if (ctx.AuthenticateFailure is not null) | |
await ctx.Response.SendErrorsAsync([new("Security", "You are unauthorized!")], 401); | |
} | |
}; | |
}) | |
.AddAuthorization() | |
.AddFastEndpoints() | |
.SwaggerDocument(); | |
var app = bld.Build(); | |
app.UseAuthentication() | |
.UseAuthorization() | |
.UseFastEndpoints( | |
c => 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