How to return a custom message if Authorization does not work in WebAPI

In my WebAPI project, I have a number of apis that are decorated with the [Authorize] attribute.

 [Authorize] public HttpResponseMessage GetCustomers() { //my api } 

If the user does not have the necessary token, an exception is returned to the user that excludes access.

But I need to, in any such case, I need to return a custom response message.

 { "StatusCode" : 403, "message": "You donot have sufficient permission" } 

How to return this custom message in case of authorization failure.

Note:

  • I use Owin-Token authentication.
  • I do not save the access token in my database or elsewhere.
+6
source share
1 answer

There are various ways to do this, but one of the best ways might be custom authorization attributes. You just need to inherit the AuthorizeAttribute method and override HandleUnauthorizedRequest() .

 public class CustomAuthorization : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("You are unauthorized to access this resource") }; } } 

and use this as ( CustomAuthorization should be used instead of Authorize )

  [CustomAuthorization] public IHttpActionResult Get() { return Ok(); } 

Otherwise, you can also catch the status code on the client side and display a custom message of your choice.

+9
source

Source: https://habr.com/ru/post/1015331/


All Articles