繁体   English   中英

Web API AuthorizeAttribute不返回自定义响应

[英]Web API AuthorizeAttribute does not return custom response

当函数返回false时,如何让IsAuthorized返回我的自定义对象?

在我的WebAPI项目中,我有一个类;

public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {

            StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse()
                    {
                        code = (int) Constants.ErrorCodes.InvalidCredentials,
                        data = "InvalidCredentials.",
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
                        invalidUserResponse);
                    // if I set this to true I am getting 401 with my custom object
                    // otherwise it gives me default error message 
                    // {"Message":"Authorization has been denied for this request."}
                    return false;
        }
    }

出于某种原因,当我从IsAuthorized函数返回false时,它不会返回我的自定义invalidUserResponse对象。 但是,如果我返回true,它将返回它。

我该如何解决这个问题?

我知道这个问题已得到解答,但我觉得这有点不对劲。 我不认为OnAuthorization应该处理未经授权请求的消息,但应由HandleUnauthorizedRequest处理。 我不确定它是否会导致将其置于OnAuthorization任何重大问题,但可能是因为基类在HandleUnauthorizedRequest写入了您的响应,因此您在获取消息时为true而非false。

这是一个微妙的事情,但OnAuthorization指向HandleUnauthorizedRequest是有原因的。 它主要是责任分离的事情,但如果你想做的不仅仅是发送错误消息,比如记录错误请求你的OnAuthorization方法可能会变得拥挤。 为了清楚起见,你应该使用给你的方法,如果没有别的。

是的我同意。 您需要实现从AuthorizeAttribute派生的自定义过滤器。

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
    base.HandleUnauthorizedRequest(actionContext);
    actionContext.Response = new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.Unauthorized,
        Content = new ObjectContent(typeof(ErrorMessage),
        new ErrorMessage()
        {
            StatusCode = (int)HttpStatusCode.Unauthorized,
            Message = Constants.UnauthorisedErrorMessage,
            ErrorCode = Constants.UnauthorisedErrorCode
        }, new JsonMediaTypeFormatter())
    };
}

你应该重写OnAuthorization方法,即使用IsAuthorized和flushs的response ,或者在你的方法强制刷新。 更有意义填充过滤器操纵它的响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM