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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)

使用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();
}

从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)

如果我删除了[Authorize]属性,那么视图缓存就像预期的那样。这是否意味着我无法将[OutputCache]放在必须具有[Authorize]的操作方法上?或者,是否需要使用静态验证回调方法用于缓存的自定义实现覆盖AuthorizeAttribute?

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

当我以me@mydomain.tld的身份访问示例缓存页面时,页面的输出被缓存,并且视图显示“此页面缓存在2011年12月 31日11:06:12 (UTC)”。如果我然后注销并登录为another@otherdomain.tld和访问该页面时,会显示“此页在12/31/2011 11:06缓存:38 AM(UTC)”。以me@mydomain.tld身份重新登录并重新访问页面会导致缓存再次显示“此页面缓存在2011年12月 31日11:06:12 (UTC)”。进一步的登录/注销尝试显示,不同的输出将被缓存并返回,具体取决于用户。

这导致我相信输出是基于用户单独缓存的,这是我的VaryByCustom =“User”设置和覆盖的意图。问题是它不适用于Azure的分布式缓存提供程序。埃文,你回答只是缓存公共内容仍然存在?

我挖掘了源代码,并发现开箱即用的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);
}

CacheValidationHandler将缓存验证委托给protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase)当然不是静态的。为什么它不是静态的一个原因是,正如在上面的重要评论中指出的那样,它会调用protected virtual bool AuthorizeCore(HttpContextBase)

为了从静态缓存验证回调方法执行任何AuthorizeCore逻辑,它需要知道AuthorizeAttribute实例的用户和角色属性。但是,似乎并没有简单的插件方式。我必须重写OnAuthorization才能将这两个值放入HttpContext(Items集合?),然后重写OnCacheAuthorization以将其取消。但是那味道很脏。

如果我们小心地使用OutputCache属性中的VaryByCustom =“User”属性,我们是否可以重写OnCacheAuthorization以始终返回HttpValidationStatus.Valid?当action方法没有OutputCache属性时,我们不需要担心这个回调会被调用,是否正确?如果我们确实有一个没有VaryByCustom =“User”的OutputCache属性,那么显然页面可以返回任何缓存版本,而不管哪个用户请求创建了缓存副本。这有多危险?

提问于
用户回答回答于

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

我认为可以帮助你的部分是一种自定义的授权属性,它的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;
}
用户回答回答于

我已经回到这个问题,经过一番修改之后,得出结论,当使用Azure分布式缓存时,不能使用System.Web.Mvc.AuthorizeAttribute开箱System.Web.Mvc.OutputCacheAttribute 即用的盒子。主要原因是,正如原始问题中的错误消息所述,验证回调方法必须是静态的才能将其用于Azure的DistributedCache。MVC Authorize属性中的缓存回调方法是一种实例方法。

我试着弄清楚如何通过从MVC源生成AuthorizeAttribute的副本,重命名它,将它连接到OutputCache连接到Azure的操作并进行调试,从而实现它的工作。缓存回调方法不是静态的原因是,为了授权,属性需要根据构造属性时设置的用户和角色属性值来检查HttpContext的用户。这里是相关的代码:

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

缓存验证回调

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

如所见,高速缓存验证回调最终会调用AuthorizeCore,这是另一种实例方法(受保护的虚拟)。AuthorizeCore在OnAuthorization中也被调用,它有三个主要的功能:

  1. 检查HttpContextBase.User.Identity.IsAuthenticated ==是否为true
  2. 如果该属性具有非空Users字符串属性,则检查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;
}

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

我的第一个尝试是通过使用object data参数传递这些值到回调CacheValidateHandler。即使在引入静态方法之后,这仍然不起作用,并导致相同的异常。我希望对象数据会被序列化,然后在回调期间传递回验证处理程序。显然情况并非如此,当尝试这样做时,Azure的分布式缓存仍然认为它是非静态回调,导致出现相同的异常和消息。

// this won't work
cachePolicy.AddValidationCallback(CacheValidateHandler, new object() /* data */);

我的第二个尝试是将值添加到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));
}

然而...

尽管似乎没有办法将用户和角色属性值传递回缓存验证回调处理程序,但HttpContext传递给它的实际上具有正确的用户主体。此外,我目前想要合并[Authorize]和[OutputCache]的操作都不会将Users或Roles属性传递给AuthorizeAttribute构造函数。

所以,可以创建一个忽略这些属性的自定义AuthenticateAttribute,并只检查以确保User.Identity.IsAuthenticated == true。如果需要针对特定​​角色进行身份验证,则还可以这样做并与OutputCache ...结合使用...但是,为了使缓存验证回调方法静态化,您需要每个(一组)角色的独特属性。我已经打磨了一下后,我会回来并发布代码。

扫码关注云+社区