注入 GlimpseSecurityPolicy

Injection of GlimpseSecurityPolicy

我想实现我自己的 IRuntimePolicy。我正在按照给定的示例进行操作,但是我需要访问我们的数据库,或者最好是注入我们的 UserSession 对象。

何时在运行时创建安全对象?这可能吗?我还没有找到任何例子。

我相信我们使用 Ninject 3.2.3(或最新的 MVC 5)。

我想像

public class GlimpseSecurityPolicy : IRuntimePolicy
    {
        private readonly IAclManager aclManager;
        private readonly IUserSession userSession;

        public GlimpseSecurityPolicy(IUserSession userSession, IAclManager aclManager)
        {
            this.userSession = userSession;
            this.aclManager = aclManager;
        }

        public RuntimeEvent ExecuteOn
        {
            // check policy when request ends and when executing a resource (like glimpse.axd)
            get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
        }

        public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
        {
            if (!this.aclManager.IsUserAllowed(UserAction.AccessGlimpse, this.userSession.GetUser()))
            {
                return RuntimePolicy.Off;
            }

            return RuntimePolicy.On;
        }
    }

最终,我们只有一个选择:使用DependencyResolver.Current.GetService<IThing>()

代码结果简单而丑陋:

public class GlimpseSecurityPolicy : IRuntimePolicy
    {
        public RuntimeEvent ExecuteOn => RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource;

        public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
        {
            var aclManager = DependencyResolver.Current.GetService<IAclManager>();
            var userSession = DependencyResolver.Current.GetService<IUserSession>();

            if (!aclManager.IsUserAllowed(UserAction.AccessGlimpse, userSession.GetUser()))
            {
                return RuntimePolicy.Off;
            }

            return RuntimePolicy.On;
        }
    }