Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net how to set the the response body when the authorization failed?

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:

here

I specify this code in situated in startup.cs on jwtBearer configuration.

like image 487
Ramses Kouam Avatar asked Oct 14 '25 04:10

Ramses Kouam


1 Answers

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

like image 182
spaleet Avatar answered Oct 19 '25 13:10

spaleet