How to return custom message if Authorize fails in WebAPI

让人想犯罪 __ 提交于 2019-12-04 08:05:48

问题


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

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

In case user doesn't have the right token, an access denied exception is returned to the user.

But what I need is that in any such case, I need to return the custom response message as.

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

How do I return this custom message in case authorization fails.

Please note:

  • I am using Owin - Token based authentication.
  • I am not storing the access token in my database or anywhere else.

回答1:


There are different ways to do this but one of the best way could be custom authorization attributes.You just need to inherit the AuthorizeAttribute and override HandleUnauthorizedRequest() method of it.

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 like(CustomAuthorization should be used in-place of Authorize)

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

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



来源:https://stackoverflow.com/questions/42505523/how-to-return-custom-message-if-authorize-fails-in-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!