防止AuthorizeAttribute缓存 [英] Prevent AuthorizeAttribute from caching

查看:154
本文介绍了防止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.

推荐答案

仅将构造函数称为

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缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆