OWIN Authentication and Custom Response

风格不统一 提交于 2019-12-05 11:18:01

The standard message you see, which is "Authorization has been denied for this request." is created by the Authorize filter. The HandleUnauthorizedRequest method sets this message in the response.

protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
    if (actionContext == null)
    {
        throw Error.ArgumentNull("actionContext");
    }

    actionContext.Response = actionContext.ControllerContext.Request
                                 .CreateErrorResponse(
                                    HttpStatusCode.Unauthorized, 
                                      SRResources.RequestNotAuthorized);
}

SRResources.RequestNotAuthorized is what you see as the standard message.

Now, ApplyChallengeResponseAsync is called from the OnSendingHeaders callback in Katana autentication micro framework. This callback is invoked when a component writes into the response stream. In our case, when the response message created by the filter (what you see above) gets serialized, that is when the callback is invoked and ApplyChallengeResponseAsync runs. By that time, it is already too late for you to change the response. The best bet will be to override the virtual method of the Authorize filter above like this.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        var response = actionContext.Request.CreateResponse<MyError>
                                (new MyError() { Description = "My failing reason" });
        response.StatusCode = HttpStatusCode.Unauthorized;

        actionContext.Response = response;
    }
}

public class MyError
{
    public string Description { get; set; }
}

Instead of using [Authorize] on the controller or action method, use [MyAuthorize].

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