I have to show a custom (JSON) response body when the authorization fails in my API. By default I have this message: "Unauthorized", but I would like to return a JSON containing a customized code error, a message and some other details. Here is an example of what I did:
o.Events = new JwtBearerEvents
{
    OnChallenge = async (context) =>
    {
        if (!context.Request.Headers.ContainsKey("Authorization"))
        {
            context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The authorization parameter is not given or the token passed is empty";
        }
    },
    OnAuthenticationFailed = async (context) =>
    {
        await context.HttpContext.Response.WriteAsync("ramses");
        context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The token is invalid or has expired";
    },
};
I tried with WriteAsync method of HttpContext.Response but the message I defined does not appear, only the reason phrase appears correctly.
Here is the image of the result in my API:

I specify this code in situated in startup.cs on jwtBearer configuration.
I've used this in my code and it works very well
.AddJwtBearer(o => {
    
   o.RequireHttpsMetadata = false;
   o.SaveToken = false;
   o.TokenValidationParameters = tokenValidationParameters;
   
   o.Events = new JwtBearerEvents {
       
        OnAuthenticationFailed = c => {
            c.NoResult();
            c.Response.StatusCode = 500;
            c.Response.ContentType = "text/plain";
            return c.Response.WriteAsync(c.Exception.ToString());
        },
        
        OnChallenge = context => {
            context.HandleResponse();
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            var result = JsonConvert.SerializeObject(new {
               status = "un-authorized",
               message = "un-authorized"
            });
            return context.Response.WriteAsync(result);
        },
        
        OnForbidden = context => {
            context.Response.StatusCode = 403;
            context.Response.ContentType = "application/json";
            var result = JsonConvert.SerializeObject(new {
               status = "un-authorized",
               message = "un-authorized"
            });
            return context.Response.WriteAsync(result);
        }
        
   };
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With