如果WebAPI中的授权失败,如何返回自定义消息 [英] How to return custom message if Authorize fails in WebAPI

查看:589
本文介绍了如果WebAPI中的授权失败,如何返回自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的WebAPI项目中,我有许多用[Authorize]属性修饰的api.

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.

请注意:

  • 我正在使用Owin-基于令牌的身份验证.
  • 将访问令牌存储在数据库或其他任何地方.
  • I am using Owin - Token based authentication.
  • I am not storing the access token in my database or anywhere else.

推荐答案

执行此操作的方法不同,但是最好的方法之一是自定义授权属性.您只需要继承AuthorizeAttribute并覆盖HandleUnauthorizedRequest()方法.

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

并像这样使用((CustomAuthorization应该代替Authorize)

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.

这篇关于如果WebAPI中的授权失败,如何返回自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆