为什么我在使用Azure缓存(.NET MVC3应用程序)时无法组合[Authorize]和[OutputCache]属性?

dan*_*wig 19 outputcache azure authorize-attribute asp.net-mvc-3

使用Windows Azure Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider作为MVC3应用程序的outputCache提供程序.以下是相关的操作方法:

[ActionName("sample-cached-page")]
[OutputCache(Duration = 300, VaryByCustom = "User", 
    Location = OutputCacheLocation.Server)]
[Authorize(Users = "me@mydomain.tld,another@otherdomain.tld")]
public virtual ActionResult SampleCachedPage()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

从Web浏览器加载此视图时出现以下异常:

System.Configuration.Provider.ProviderException: When using a custom output cache provider like 'DistributedCache', only the following expiration policies and cache features are supported: file dependencies, absolute expirations, static validation callbacks and static substitution callbacks.

System.Configuration.Provider.ProviderException: When using a custom output cache provider like 'DistributedCache', only the following expiration policies and cache features are supported:  file dependencies, absolute expirations, static validation callbacks and static substitution callbacks.
   at System.Web.Caching.OutputCache.InsertResponse(String cachedVaryKey, CachedVary cachedVary, String rawResponseKey, CachedRawResponse rawResponse, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp)
   at System.Web.Caching.OutputCacheModule.OnLeave(Object source, EventArgs eventArgs)
   at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Run Code Online (Sandbox Code Playgroud)

如果我删除[Authorize]属性,视图将按预期缓存.这是否意味着我不能将[OutputCache]放在必须具有[Authorize]的操作方法上?或者,我是否需要使用对缓存使用静态验证回调方法的自定义实现来覆盖AuthorizeAttribute?

更新1

在Evan回答之后,我在IIS Express(Azure之外)中测试了上述操作方法.这是我对OutputCache属性上的VaryByCustom ="User"属性的覆盖:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    return "User".Equals(custom, StringComparison.OrdinalIgnoreCase)
        ? Thread.CurrentPrincipal.Identity.Name
        : base.GetVaryByCustomString(context, custom);
}
Run Code Online (Sandbox Code Playgroud)

当我以me@mydomain.tld访问示例缓存页面时,页面的输出将被缓存,并且视图显示"此页面于2011年12月 31 上午11:06:12 (UTC)缓存".如果我然后注销并登录为another@otherdomain.tld和访问该页面时,会显示"此页在12/31/2011 11:06缓存:38 AM(UTC)".在重新登录为me@mydomain.tld和重温页面就会导致缓存,显示"此页在12/31/2011 11:06缓存:12个 AM(UTC)"一次.进一步的登录/退出尝试表明根据用户缓存和返回不同的输出.

这让我相信输出是根据用户单独缓存的,这是我的VaryByCustom ="User"设置和覆盖的意图.问题是它不适用于Azure的分布式缓存提供程序.Evan,你回答的问题只是缓存公共内容仍然存在吗?

更新2

我挖出了源代码,发现开箱即用的AuthorizeAttribute确实有一个非静态验证回调.以下摘录自OnAuthorization:

if (AuthorizeCore(filterContext.HttpContext)) {
    // ** IMPORTANT **
    // Since we're performing authorization at the action level, the authorization code runs
    // after the output caching module. In the worst case this could allow an authorized user
    // to cause the page to be cached, then an unauthorized user would later be served the
    // cached page. We work around this by telling proxies not to cache the sensitive page,
    // then we hook our custom authorization code into the caching mechanism so that we have
    // the final say on whether a page should be served from the cache.

    HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
    cachePolicy.SetProxyMaxAge(new TimeSpan(0));
    cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else {
    HandleUnauthorizedRequest(filterContext);
}
Run Code Online (Sandbox Code Playgroud)

CacheValidationHandler委托缓存验证protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase),当然这不是静态的.它不是静态的一个原因是,正如上面的重要评论所述,它会调用它protected virtual bool AuthorizeCore(HttpContextBase).

为了从静态缓存验证回调方法执行任何AuthorizeCore逻辑,它需要知道AuthorizeAttribute实例的Users和Roles属性.然而,似乎没有一种简单的方法可以插入.我必须重写OnAuthorization以将这两个值放入HttpContext(Items集合?)中,然后重写OnCacheAuthorization以使它们退出.但那闻起来很脏.

如果我们小心使用OutputCache属性中的VaryByCustom ="User"属性,我们可以覆盖OnCacheAuthorization以始终返回HttpValidationStatus.Valid吗?当action方法没有OutputCache属性时,我们不需要担心这个回调被调用,对吗?如果我们确实有一个没有VaryByCustom ="User"的OutputCache属性,那么很明显,无论哪个用户请求创建了缓存副本,页面都可以返回任何缓存版本.这有多危险?

one*_*mer 9

缓存发生在Action之前.您可能需要自定义授权机制来处理缓存方案.

查看我之前发布的一个问题 - MVC自定义身份验证,授权和角色实现.

我认为可以帮助你的部分是一个自定义授权属性谁的OnAuthorize()方法处理缓存.

下面是一个代码块,例如:

/// <summary>
/// Uses injected authorization service to determine if the session user 
/// has necessary role privileges.
/// </summary>
/// <remarks>As authorization code runs at the action level, after the 
/// caching module, our authorization code is hooked into the caching 
/// mechanics, to ensure unauthorized users are not served up a 
/// prior-authorized page. 
/// Note: Special thanks to TheCloudlessSky on StackOverflow.
/// </remarks>
public void OnAuthorization(AuthorizationContext filterContext)
{
    // User must be authenticated and Session not be null
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated || filterContext.HttpContext.Session == null)
        HandleUnauthorizedRequest(filterContext);
    else {
        // if authorized, handle cache validation
        if (_authorizationService.IsAuthorized((UserSessionInfoViewModel)filterContext.HttpContext.Session["user"], _authorizedRoles)) {
            var cache = filterContext.HttpContext.Response.Cache;
            cache.SetProxyMaxAge(new TimeSpan(0));
            cache.AddValidationCallback((HttpContext context, object o, ref HttpValidationStatus status) => AuthorizeCache(context), null);
        }
        else
            HandleUnauthorizedRequest(filterContext);             
    }
}

/// <summary>
/// Ensures that authorization is checked on cached pages.
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public HttpValidationStatus AuthorizeCache(HttpContext httpContext)
{
    if (httpContext.Session == null)
        return HttpValidationStatus.Invalid;
    return _authorizationService.IsAuthorized((UserSessionInfoViewModel) httpContext.Session["user"], _authorizedRoles) 
        ? HttpValidationStatus.Valid 
        : HttpValidationStatus.IgnoreThisRequest;
}
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,这太复杂了.我们所有的Auth属性都需要检查角色等,所以我认为我不能让它工作.您是否曾使用基于角色的Auth与Azure输出缓存提供程序一起工作? (2认同)

dan*_*wig 7

我回过头来看看这个问题,经过一些修补,得出的结论是,在使用Azure DistributedCache时,你无法使用System.Web.Mvc.AuthorizeAttribute开箱System.Web.Mvc.OutputCacheAttribute 即用的开箱即用.主要原因是,正如原始问题中的错误消息所述,验证回调方法必须是静态的,才能将其与Azure的DistributedCache一起使用.MVC Authorize属性中的缓存回调方法是实例方法.

我尝试通过从MVC源创建AuthorizeAttribute的副本,重命名它,将其连接到OutputCache连接到Azure的操作以及调试来弄清楚如何使其工作.缓存回调方法不是静态的原因是,为了进行授权,属性需要针对构造属性时设置的Users和Roles属性值检查HttpContext的User.这是相关代码:

OnAuthorization

public virtual void OnAuthorization(AuthorizationContext filterContext) {
    //... code to check argument and child action cache

    if (AuthorizeCore(filterContext.HttpContext)) {
        // Since we're performing authorization at the action level, 
        // the authorization code runs after the output caching module. 
        // In the worst case this could allow an authorized user
        // to cause the page to be cached, then an unauthorized user would 
        // later be served the cached page. We work around this by telling 
        // proxies not to cache the sensitive page, then we hook our custom
        // authorization code into the caching mechanism so that we have
        // the final say on whether a page should be served from the cache.

        HttpCachePolicyBase cachePolicy = filterContext
            .HttpContext.Response.Cache;
        cachePolicy.SetProxyMaxAge(new TimeSpan(0));
        cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
    }
    else {
        HandleUnauthorizedRequest(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

缓存验证回调

private void CacheValidateHandler(HttpContext context, object data, 
    ref HttpValidationStatus validationStatus) {
    validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}

// This method must be thread-safe since it is called by the caching module.
protected virtual HttpValidationStatus OnCacheAuthorization
    (HttpContextBase httpContext) {
    if (httpContext == null) {
        throw new ArgumentNullException("httpContext");
    }

    bool isAuthorized = AuthorizeCore(httpContext);
    return (isAuthorized) 
        ? HttpValidationStatus.Valid 
        : HttpValidationStatus.IgnoreThisRequest;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,缓存验证回调最终调用AuthorizeCore,这是另一个实例方法(受保护的虚拟).在OnAuthorization期间也调用的AuthorizeCore做了3件主要的事情:

  1. 检查HttpContextBase.User.Identity.IsAuthenticated == true

  2. 如果该属性具有非空的用户字符串属性,请检查HttpContextBase.User.Identity.Name是否与逗号分隔值之一匹配.

  3. 如果该属性具有非空的Roles字符串属性,则检查其中一个以逗号分隔的值的HttpContextBase.User.IsInRole.

AuthorizeCore

// This method must be thread-safe since it is called by the thread-safe
// OnCacheAuthorization() method.
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
    if (httpContext == null) {
        throw new ArgumentNullException("httpContext");
    }

    IPrincipal user = httpContext.User;
    if (!user.Identity.IsAuthenticated) {
        return false;
    }

    if (_usersSplit.Length > 0 && !_usersSplit.Contains
        (user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
        return false;
    }

    if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
         return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

当您只是尝试使验证回调方法为静态时,代码将无法编译,因为它需要访问这些_rolesSplit和_usersSplit字段,这些字段基于公共用户和角色属性.

我的第一次尝试是使用the的object data参数将这些值传递给回调CacheValidateHandler.即使在引入静态方法之后,这仍然无效,并导致相同的异常.我希望对象数据将被序列化,然后在回调期间传递回验证处理程序.显然情况并非如此,当您尝试执行此操作时,Azure的DistributedCache仍将其视为非静态回调,从而导致相同的异常和消息.

// this won't work
cachePolicy.AddValidationCallback(CacheValidateHandler, new object() /* data */);
Run Code Online (Sandbox Code Playgroud)

我的第二次尝试是将值添加到HttpContext.Items集合中,因为实例HttpContext会自动传递给处理程序.这也不起作用.将HttpContext传递到CacheValidateHandler 是不一样的情况下,关于存在的filterContext.HttpContext属性.事实上,当CacheValidateHandler执行时,它有一个空的Session并且总是有一个空的Items集合.

// this won't work
private void CacheValidateHandler(HttpContext context, object data, 
    ref HttpValidationStatus validationStatus) {
    Debug.Assert(!context.Items.Any()); // even after I put items into it
    validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
Run Code Online (Sandbox Code Playgroud)

然而...

即使似乎没有办法将Users&Roles属性值传递回缓存验证回调处理程序,HttpContext传递给它的确实具有正确的User Principal.此外,我当前想要组合[Authorize]和[OutputCache]的任何操作都没有将Users或Roles属性传递给AuthorizeAttribute构造函数.

因此,可以创建一个忽略这些属性的自定义AuthenticateAttribute,并且只检查以确保User.Identity.IsAuthenticated == true.如果您需要针对特定​​角色进行身份验证,您也可以这样做并与OutputCache结合使用...但是,您需要为每个(一组)角色提供一个不同的属性,以便使缓存验证回调方法成为静态.在我稍微完善它之后,我会回来并发布代码.