Skip to content

Instantly share code, notes, and snippets.

@dj-nitehawk
Last active August 26, 2024 08:39
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();
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