FastEndpoints / FastEndpoints

A light-weight REST API development framework for ASP.NET 6 and newer.
https://fast-endpoints.com
MIT License
4.75k stars 283 forks source link

JWT 401 unauthorized custom response #57

Closed zhixXiang closed 2 years ago

zhixXiang commented 2 years ago

How can I respond the status 401 with message or my own error class? Currently send only 401 without message.

dj-nitehawk commented 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.

zhixXiang commented 2 years ago

Thank you, this is what I need!

dj-nitehawk commented 6 months ago

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();