OWIN身份验证和自定义响应

5
我创建了一个自定义的BasicAuthenticationMiddleware,它使用一个BasicAuthenticationHandler来验证客户端请求到WebAPI的身份。

BasicAuthenticationHandler派生自AuthenticationHandler< TOptions >基类。

一切都运行良好,并且我已经实现了AuthenticateCoreAsync,在这里进行验证逻辑

ApplyChallengeResponseAsync在未经过身份验证的请求时,发送WWW-Authenticate标头到客户端的逻辑。

现在我想要实现的是在响应中设置自定义Body(在ApplyChallengeResponseAsync中的IOwinResponse中),使用自定义对象,例如:

{
Code="999",
Description="My failing reason"
AdditionalInfo = "My additional infos"
}

与其使用标准信息,如:

{
    message="Authorization has been denied for this request."
}

你对此有什么建议吗?

谢谢。

1个回答

9
您所看到的标准消息是“此请求的授权已被拒绝。”,由Authorize过滤器创建。 HandleUnauthorizedRequest方法将此消息设置在响应中。
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是您看到的标准信息。

现在,ApplyChallengeResponseAsync从Katana认证微框架中的OnSendingHeaders回调中调用。当组件写入响应流时,将调用此回调。在我们的情况下,当过滤器创建的响应消息被序列化时(即您上面看到的内容),回调被调用并运行ApplyChallengeResponseAsync。到那时,您已经来不及改变响应了。最好的方法是像这样覆盖上面的Authorize过滤器的虚拟方法。

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

与其在控制器或操作方法上使用[Authorize],不如使用[MyAuthorize]


谢谢!这很简单,但我错过了它。 - Simone Belia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接