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

Time:01-28

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

CodePudding user response:

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

  •  Tags:  
  • Related