防止AuthorizeAttribute缓存

编程入门 行业动态 更新时间:2024-10-10 16:14:45
本文介绍了防止AuthorizeAttribute缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个自定义的AuthorizeAttribute,它可以检查用户是否可以访问特定操作:

I have a custom AuthorizeAttribute which checks if a user can access a particular action:

public class UserCanAccessArea : AuthorizeAttribute { readonly IPermissionService permissionService; public UserCanAccessArea() : this(DependencyResolver.Current.GetService<IPermissionService>()) { } public UserCanAccessArea(IPermissionService permissionService) { this.permissionService = permissionService; } protected override bool AuthorizeCore(HttpContextBase httpContext) { string AreaID = httpContext.Request.RequestContext.RouteData.Values["AreaID"] as string; bool isAuthorized = false; if (base.AuthorizeCore(httpContext)) isAuthorized = permissionService.UserCanAccessArea(AreaID, httpContext.User); return isAuthorized; } }

该代码仅检查用户是否已通过身份验证,然后在特定于应用程序的数据库中检查用户"对应的条目,以确定该用户是否有权访问指定的区域.当前,这只是表上的"CanAccessAreas"标志.

The code simply checks that the User is authenticated, then checks the Users corresponding entry in an application specific database to determine if the User has access to the specified Area. Currently, this is simply a "CanAccessAreas" flag on the table.

我遇到的问题是,当管理员为用户更新"CanAccessAreas"标志时,该用户仍然无法访问该区域.注意的行为:

The problem I am having is that when an Admin updates the "CanAccessAreas" flag for a User, the User still cannot access the area. Noted behaviour:

  • 注销/登录不能为用户解决此问题.
  • 在本地运行代码不会重现此行为.
  • 重新发布代码可以解决用户的问题,直到更新标志为止.
  • 每个用户都将看到一个菜单,其中显示了他们可以访问的内容.管理员更新用户标志时,此信息会立即更新.

似乎AuthorizeAttribute正在缓存结果,但是我不确定在这种情况下如何安全地防止这种情况.

It seems like the AuthorizeAttribute is caching the result but I'm unsure how to prevent this securely if this is the case.

推荐答案

仅将构造函数称为当您调用GetCustomAttributes 时,MVC似乎只调用了一次.

The constructor is only called when you call GetCustomAttributes, and MVC seems to call this only one time.

解决方案是在构造函数之外访问您的服务.

The solution is to get access to your service outside of the constructor.

例如:

public class UserCanAccessArea : AuthorizeAttribute { public UserCanAccessArea() { } protected override bool AuthorizeCore(HttpContextBase httpContext) { string AreaID = httpContext.Request.RequestContext.RouteData.Values["AreaID"] as string; bool isAuthorized = false; if (base.AuthorizeCore(httpContext)) { var permissionService = DependencyResolver.Current.GetService<IPermissionService>(); isAuthorized = permissionService.UserCanAccessArea(AreaID, httpContext.User); } return isAuthorized; } }

我没有使用Unity的经验,但是使用属性注入如@pjobs所评论.

I don't have experience with Unity, but same should be possible with Property Injection as @pjobs commented.

更多推荐

防止AuthorizeAttribute缓存

本文发布于:2023-11-01 10:58:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   AuthorizeAttribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!