6

The default ASP.NET Web Api Core behaviour for unauthorized request is to send 401/403 error with empty content. I'd like to change it by specifying some kind of Json response specifying the error.

But I struggle to find a right place where I can introduce these changes. Official documentation is of no help (read it all). I had a guess that may be I could catch UnathorizedException in my exception filter / middleware but it didn't work out (I guess it gets handled at authorization level or even not thrown at all).

So my question is how can I customize response behavior in case of unauthorized request.

SiberianGuy
  • 24,674
  • 56
  • 152
  • 266
  • Check out extension methods like `app.UseStatusCodePagesWithRedirects` and `app.UseStatusCodePages` – Developer Jan 30 '17 at 17:18
  • `https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie` go to this... it may help – Patrick Mcvay Jan 30 '17 at 17:46
  • @Developer, it seems to be specific to MVC, not Web Api – SiberianGuy Jan 31 '17 at 06:38
  • Is there such a distinction in asp.net-core? What is your auth mechanism? – Developer Jan 31 '17 at 06:41
  • @Developer, I use token authentication. Here' the code by the way: https://github.com/alexidsa/absenceapi – SiberianGuy Jan 31 '17 at 06:45
  • Still I kind feel `app.useStatusCodePages` might work, havent tried so not sure. - `app.UseStatusCodePages(async context => { context.HttpContext.Response.ContentType = "application/json"; await context.HttpContext.Response.WriteAsync( "{Status code page, status code: " + context.HttpContext.Response.StatusCode+"}"); });` -- or navigate ro some action and send your response – Developer Jan 31 '17 at 07:00
  • @SiberianGuy have you solved it? I'm migrating my web api to Asp.Net Core and get same issue now. – kvuong Mar 21 '18 at 14:21

1 Answers1

0

With .Net Core 3 (or may be earlier as well) you can write a middleware to check if the context.Response has a status of 40x and then return a custom object. Below is roughly how I did it:

if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
 var result = new MyStandardApiResponseDto
 {
  Error = new MyErrorDto
   {
    Title = "Unauthorized",
     Messages = new List<string> { "You are not authorized to access the resource. Please login again." },
   },
  Result = null
 };
 await context.Response.WriteAsync(JsonConvert.SerializeObject(result));
}
bit
  • 4,407
  • 1
  • 28
  • 50