【问题标题】:ExecuteResult method not called in HttpUnauthorizedResult derived classHttpUnauthorizedResult 派生类中未调用 ExecuteResult 方法
【发布时间】:2016-07-24 17:32:30
【问题描述】:

我需要使用 ASP.NET MVC 3 实现摘要身份验证。为此,我继承了 AuthorizeAttribute 和 HttpUnauthorizedResult。代码如下:

[AttributeUsage ( AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true )]
public class SessionAuthorize: AuthorizeAttribute {
    public override void OnAuthorization ( AuthorizationContext actionContext ) {
        try {
            if ( null != actionContext.HttpContext.Request.Headers["Authorization"] )
                // authorization is on the way
                // <...>
            else
                actionContext.Result = new HttpDigestUnauthorizedResult ();
        } catch ( Exception ex ) {
            Trace.TraceWarning ( "SessionAuthorize.OnAuthorization failed: {0}", ex.Message );
        }
        base.OnAuthorization ( actionContext );
    }
}

public class HttpDigestUnauthorizedResult: HttpUnauthorizedResult {
    public HttpDigestUnauthorizedResult () : base () {
    }
    public override void ExecuteResult ( ControllerContext context ) {
        if ( context == null )
            throw new ArgumentNullException ( "context" );
        // this is supposed to initialize digest authentification exchange
        context.HttpContext.Response.AddHeader ( "WWW-Authenticate", string.Format ( "Digest realm=\"somerealm\",qop=\"auth\",nonce=\"{0}\",opaque=\"{1}\""/*, <...>*/ ) );
        base.ExecuteResult ( context );
    }
}

控制器/动作代码如下:

public class DefaultController: Controller {
    [SessionAuthorize]
    public ViewResult Index () {
        return View ();
    }
}

所以它没有做任何特别的事情。

但是,覆盖的ExecuteResult 永远不会被调用,只会返回标准的 401 页面。我在这里想念什么?应该从哪里调用ExecuteResult?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-3 digest-authentication


    【解决方案1】:

    正确的模式是:使用AuthorizeCore(返回bool)来判断当前请求是否被授权,并在HandleUnauthorizedRequest方法中处理那些未经授权的请求。将所有内容都放在OnAuthorization 中是不正确的,因为根据the source code,在某些情况下会调用OnCacheAuthorization 方法而不是OnAuthorization。

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.Headers["Authorization"] == null)
        {
            return false;
        }
    
        return base.AuthorizeCore(httpContext);
    }
    
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpDigestUnauthorizedResult();
    }
    

    【讨论】:

    • 谢谢,这正是问题所在。
    猜你喜欢
    • 2012-05-31
    • 2014-03-17
    • 2014-09-05
    • 2019-11-16
    • 2022-01-02
    • 2016-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多