使用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?
更新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);
}
当我以me@mydomain.tld访问示例缓存页面时,页面的输出被缓存,并且视图显示“此页面缓存于12/31/2011 11:06: 12 AM(UTC)“。如果我然后退出并以another@otherdomain.tld登录并访问该页面,则会显示“此页面已于2011年12月31日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);
}
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属性,那么很明显,无论哪个用户请求创建了缓存副本,页面都可以返回任何缓存版本。这有多大的风险?
答案 0 :(得分:9)
缓存发生在Action之前。您可能需要自定义授权机制来处理缓存方案。
查看我暂时发布的问题 - MVC Custom Authentication, Authorization, and Roles Implementation。
我认为可以帮助您的部分是一个自定义授权属性,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;
}
答案 1 :(得分:7)
我回到这个问题,经过一些修补,得出结论:不能使用开箱即用System.Web.Mvc.AuthorizeAttribute
以及开箱即用{ {1}} 使用Azure DistributedCache 时。主要原因是,正如原始问题中的错误消息所述,验证回调方法必须是静态的,才能将其与Azure的DistributedCache一起使用。 MVC Authorize属性中的缓存回调方法是实例方法。
我尝试通过从MVC源创建AuthorizeAttribute的副本,重命名它,将其连接到OutputCache连接到Azure的操作以及调试来弄清楚如何使其工作。缓存回调方法不是静态的原因是,为了授权,属性需要针对构造属性时设置的Users和Roles属性值检查HttpContext的User。以下是相关代码:
<强> OnAuthorization 强>
System.Web.Mvc.OutputCacheAttribute
缓存验证回调
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);
}
}
如您所见,缓存验证回调最终调用AuthorizeCore,这是另一个实例方法(受保护的虚拟)。在OnAuthorization期间也调用的AuthorizeCore做了3件主要的事情:
检查HttpContextBase.User.Identity.IsAuthenticated == true
如果属性具有非空的用户字符串属性,请检查HttpContextBase.User.Identity.Name是否与逗号分隔值匹配。
如果该属性具有非空的Roles字符串属性,请检查其中一个以逗号分隔的值的HttpContextBase.User.IsInRole。
<强> AuthorizeCore 强>
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;
}
当您只是尝试使验证回调方法为静态时,代码将无法编译,因为它需要访问这些_rolesSplit和_usersSplit字段,这些字段基于公共用户和角色属性。
我的第一次尝试是使用// 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;
}
的{{1}}参数将这些值传递给回调。即使在引入静态方法之后,这仍然无效,并导致相同的异常。我希望对象数据将被序列化,然后在回调期间传递回验证处理程序。显然情况并非如此,当您尝试这样做时,Azure的DistributedCache仍然认为它是非静态回调,导致相同的异常&amp;消息。
object data
我的第二次尝试是将值添加到CacheValidateHandler
集合,因为// this won't work
cachePolicy.AddValidationCallback(CacheValidateHandler, new object() /* data */);
的实例会自动传递给处理程序。这也不起作用。传递给HttpContext.Items
的HttpContext
与HttpContext
媒体资源上存在的实例 不同。实际上,当CacheValidateHandler执行时,它有一个空的Session,并且总是有一个空的Items集合。
CacheValidateHandler
即使似乎没有办法通过用户&amp;将属性值转换回缓存验证回调处理程序,传递给它的filterContext.HttpContext
确实具有正确的用户主体。此外,我当前想要组合[Authorize]和[OutputCache]的任何操作都没有将Users或Roles属性传递给AuthorizeAttribute构造函数。
因此,可以创建一个忽略这些属性的自定义AuthenticateAttribute,并且只检查以确保// 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));
}
。如果您需要针对特定角色进行身份验证,您也可以这样做并与OutputCache结合使用...但是,您需要为每个(一组)角色提供一个不同的属性,以便使缓存验证回调方法成为静态。我会稍微打磨一下后再回来发布代码。
答案 2 :(得分:2)
你是正确的橄榄油。缓存的工作原理是缓存Action的整个输出(包括所有属性),然后将结果返回到后续调用,而不实际调用任何代码。
因此,您无法缓存和检查授权,因为通过缓存您不会调用任何代码(包括授权)。因此,任何缓存的内容都必须是公开的。