【问题标题】:OWIN Authentication and Custom ResponseOWIN 身份验证和自定义响应
【发布时间】:2014-11-25 04:38:46
【问题描述】:

我创建了一个 custom BasicAuthenticationMiddleware,它使用 BasicAuthenticationHandler 来验证从客户端到 WebAPI 的请求。

BasicAuthenticationHandler 派生自 AuthenticationHandler 基类。

一切正常,我实现了

AuthenticateCoreAsync 验证逻辑发生在哪里

ApplyChallengeResponseAsync 如果请求未经过身份验证,逻辑会将 WWW-Authenticate 标头发送到客户端。

我现在想要实现的是在响应中设置一个自定义主体(IOwinResponse,在 ApplyChallengeResponseAsync 内部,带有一个自定义对象,例如:

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

而不是像标准消息那样

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

您对此有什么建议吗?

谢谢

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api owin asp.net-web-api2


    【解决方案1】:

    您看到的标准消息是“此请求的授权已被拒绝”。由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]

    【讨论】:

    • 谢谢!这很简单,但我错过了。
    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2019-06-19
    • 2016-12-31
    • 2014-07-06
    • 2019-10-07
    • 2020-04-01
    相关资源
    最近更新 更多