Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Created June 4, 2024 04:18
Show Gist options
  • Save dj-nitehawk/9654ae91808df04abcfd8ec21b373a7b to your computer and use it in GitHub Desktop.
Save dj-nitehawk/9654ae91808df04abcfd8ec21b373a7b to your computer and use it in GitHub Desktop.
Sending custom response on JWT Bearer Auth failure
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