Closed zhixXiang closed 2 years ago
have a look at the "solution 1" of the following article: https://referbruv.com/blog/posts/building-custom-responses-for-unauthorized-requests-in-aspnet-core
basically when jwt auth fails, the 401 is being thrown by the authentication middleware before it reaches fastendpoints.
so, you need to register the auth middleware yourself instead of using the built-in AddAuthenticationJWTBearer
and handle the JwtBearerEvents
yourself and do whatever you like with the response.
Thank you, this is what I need!
updated example:
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();
How can I respond the status 401 with message or my own error class? Currently send only 401 without message.