在HttpUnauthorizedResult派生类中没有调用ExecuteResult方法

时间:2016-04-05 00:27:58

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

我需要使用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

1 个答案:

答案 0 :(得分:2)

正确的模式是:使用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();
}