public IEnumerable <PolicyResult> EnforcePolicies(ISecurityContext context) { if (_policies.Count.Equals(0)) { throw ExceptionFactory.CreateConfigurationErrorsException("You must add at least 1 policy for controller {0} action {1}.".FormatWith(ControllerName, ActionName)); } var defaultResultsCacheLifecycle = SecurityConfigurationProvider.Invoke().Advanced.DefaultResultsCacheLifecycle; var cache = SecurityCache.CacheProvider.Invoke(); var results = new List <PolicyResult>(); foreach (var policy in _policies.Select(NonLazyIfPolicyHasCacheKeyProvider())) { var strategy = GetExecutionCacheStrategyForPolicy(policy, defaultResultsCacheLifecycle); var cacheKey = PolicyResultCacheKeyBuilder.CreateFromStrategy(strategy, policy, context); var result = cache.Get <PolicyResult>(cacheKey, strategy.CacheLifecycle.ToLifecycle()); if (result == null) { result = policy.Enforce(context); cache.Store(result, cacheKey, strategy.CacheLifecycle.ToLifecycle()); } results.Add(result); if (result.ViolationOccured) { break; } } return(results.AsReadOnly()); }
public ActionResult HandleSecurityFor(string controllerName, string actionName, ISecurityContext securityContext) { if (controllerName.IsNullOrEmpty()) { throw new ArgumentException("Controllername must not be null or empty", "controllerName"); } if (actionName.IsNullOrEmpty()) { throw new ArgumentException("Actionname must not be null or empty", "actionName"); } if (securityContext == null) { throw new ArgumentNullException("securityContext", "Security context must not be null"); } var configuration = ServiceLocator.Current.Resolve <ISecurityConfiguration>(); var policyContainer = configuration.PolicyContainers.GetContainerFor(controllerName, actionName); if (policyContainer != null) { var results = policyContainer.EnforcePolicies(securityContext); if (results.Any(x => x.ViolationOccured)) { var result = results.First(x => x.ViolationOccured); var policyViolationException = new PolicyViolationException(result); var violationHandlerSelector = ServiceLocator.Current.Resolve <IPolicyViolationHandlerSelector>(); var matchingHandler = violationHandlerSelector.FindHandlerFor(policyViolationException) ?? new ExceptionPolicyViolationHandler(); return(matchingHandler.Handle(policyViolationException)); } return(null); } if (configuration.IgnoreMissingConfiguration) { return(null); } throw ExceptionFactory.CreateConfigurationErrorsException("Security has not been configured for controller {0}, action {1}".FormatWith(controllerName, actionName)); }