public static ISecurityConfiguration SetupFluentSecurity() { SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(Helpers.SecurityHelper.UserIsAuthenticated); configuration.GetRolesFrom(Helpers.SecurityHelper.UserRoles); configuration.For <HomeController>().Ignore(); configuration.For <AccountController>(x => x.LogInAsAdministrator()).DenyAuthenticatedAccess(); configuration.For <AccountController>(x => x.LogInAsPublisher()).DenyAuthenticatedAccess(); configuration.For <AccountController>(x => x.LogOut()).DenyAnonymousAccess(); configuration.For <ExampleController>(x => x.DenyAnonymousAccess()).DenyAnonymousAccess(); configuration.For <ExampleController>(x => x.DenyAuthenticatedAccess()).DenyAuthenticatedAccess(); configuration.For <ExampleController>(x => x.RequireAdministratorRole()).RequireRole(UserRole.Administrator); configuration.For <ExampleController>(x => x.RequirePublisherRole()).RequireRole(UserRole.Publisher); configuration.For <AdminController>().AddPolicy(new AdministratorPolicy()); configuration.For <AdminController>(x => x.Delete()).DelegatePolicy("LocalOnlyPolicy", context => HttpContext.Current.Request.IsLocal ); configuration.For <Areas.ExampleArea.Controllers.HomeController>().DenyAnonymousAccess(); configuration.For <Areas.ExampleArea.Controllers.HomeController>(x => x.PublishersOnly()).RequireRole(UserRole.Publisher); configuration.For <Areas.ExampleArea.Controllers.HomeController>(x => x.AdministratorsOnly()).RequireRole(UserRole.Administrator); }); return(SecurityConfiguration.Current); }
public static void Configure() { SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated); configuration.ForAllControllers().DenyAnonymousAccess(); configuration.For <AccountController>(x => x.LogIn()).Ignore(); configuration.For <HomeController>(x => x.Create()).RequireRole(new object[] { "Admin" }); configuration.ResolveServicesUsing(type => { if (type == typeof(IPolicyViolationHandler)) { var types = Assembly .GetAssembly(typeof(MvcApplication)) .GetTypes() .Where(x => typeof(IPolicyViolationHandler).IsAssignableFrom(x)).ToList(); var handlers = types.Select(t => Activator.CreateInstance(t) as IPolicyViolationHandler).ToList(); return(handlers); } return(Enumerable.Empty <object>()); }); }); }
public void Should_set_the_result_of_the_filtercontext() { // Arrange SecurityConfigurator.Configure(policy => { policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue); policy.For <BlogController>(x => x.Index()).DenyAnonymousAccess(); }); var expectedResult = new ViewResult { ViewName = "SomeViewName" }; var securityHandler = MockRepository.GenerateMock <ISecurityHandler>(); securityHandler.Expect(x => x.HandleSecurityFor(typeof(BlogController).FullName, "Index")).Repeat.Once().Return(expectedResult); securityHandler.Replay(); var handleSecurityAttribute = new HandleSecurityAttribute(securityHandler); var filterContext = MvcHelpers.GetFilterContextFor <BlogController>(x => x.Index()); // Act handleSecurityAttribute.OnActionExecuting(filterContext); // Assert Assert.That(filterContext.Result, Is.EqualTo(expectedResult)); securityHandler.VerifyAllExpectations(); }
public static void Configure() { SecurityConfigurator.Configure(c => { c.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated); c.GetRolesFrom(() => (HttpContext.Current.Session["Roles"] as string[])); // Blanked Deny All c.ForAllControllers().DenyAnonymousAccess(); // Publicly Accessible Areas c.For <LoginController>().Ignore(); // This is the part for finding all of the classes that inherit // from IPolicyViolationHandler so you don't have to use an IOC // Container. c.ResolveServicesUsing(type => { if (type == typeof(IPolicyViolationHandler)) { var types = Assembly .GetAssembly(typeof(MvcApplication)) .GetTypes() .Where(x => typeof(IPolicyViolationHandler).IsAssignableFrom(x)).ToList(); var handlers = types.Select(t => Activator.CreateInstance(t) as IPolicyViolationHandler).ToList(); return(handlers); } return(Enumerable.Empty <object>()); }); }); }
public void Should_set_the_result_of_the_filtercontext() { // Arrange SecurityConfigurator.Configure(policy => { policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue); policy.For <BlogController>(x => x.Index()).DenyAnonymousAccess(); }); var expectedResult = new ViewResult { ViewName = "SomeViewName" }; var securityHandler = new Mock <ISecurityHandler>(); securityHandler.Setup(x => x.HandleSecurityFor(typeof(BlogController).FullName, "Index", It.IsAny <ISecurityContext>())).Returns(expectedResult); var handleSecurityAttribute = new HandleSecurityAttribute(securityHandler.Object); var filterContext = MvcHelpers.GetAuthorizationContextFor <BlogController>(x => x.Index()); // Act handleSecurityAttribute.OnAuthorization(filterContext); // Assert Assert.That(filterContext.Result, Is.EqualTo(expectedResult)); }
private void SetupSecurity() { SecurityConfigurator.Configure(configuration => { // Let FluentSecurity know how to get the authentication status of the current user configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated); // This is where you set up the policies you want FluentSecurity to enforce on your controllers and actions configuration.For <HomeController>().Ignore(); configuration.For <AccountController>().DenyAuthenticatedAccess(); //configuration.For<AccountController>(x => x.ChangePassword()).DenyAnonymousAccess(); configuration.For <AccountController>(x => x.LogOff()).DenyAnonymousAccess(); configuration.For <AbscenseController>().AddPolicy(new ShouldBelongToInstancePolicy()); configuration.For <ExpenseController>().AddPolicy(new ShouldBelongToInstancePolicy()); configuration.For <TransferController>().AddPolicy(new ShouldBelongToInstancePolicy()); configuration.For <CategoryController>().AddPolicy(new ShouldBelongToInstancePolicy()); configuration.For <InstanceController>().DenyAnonymousAccess(); configuration.For <InstanceController>(x => x.Details(default(Guid))).AddPolicy(new ShouldBelongToInstancePolicy()); configuration.Advanced.ModifySecurityContext(context => { var id = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)).Values["instanceId"]; if (id != null) { context.Data.InstanceId = Guid.Parse(id.ToString()); } } ); }); GlobalFilters.Filters.Add(new HandleSecurityAttribute(), -1); }
public void Should_load_lazy_policy_with_cache_key_exactly_twice_during_execution_with_caching_on() { // Arrange var callsToContainer = 0; var policy = new LazyLoadedPolicyWithCacheKey(); FakeIoC.GetAllInstancesProvider = () => { callsToContainer++; return(new List <object> { policy }); }; SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(TestDataFactory.ValidIsAuthenticatedFunction); configuration.ResolveServicesUsing(FakeIoC.GetAllInstances); configuration.Advanced.SetDefaultResultsCacheLifecycle(Cache.PerHttpRequest); }); var context = new MockSecurityContext(); var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender()); policyContainer.AddPolicy <LazyLoadedPolicyWithCacheKey>(); // Act policyContainer.EnforcePolicies(context); policyContainer.EnforcePolicies(context); // Assert Assert.That(callsToContainer, Is.EqualTo(2)); Assert.That(policy.CacheKeyCallCount, Is.EqualTo(2), "Did not get the custom cache key the expected amount of times"); Assert.That(policy.EnforceCallCount, Is.EqualTo(1), "Did not call enforce the expected amount of times"); }
public static void RegisterSecurityRules() { SecurityConfigurator.Configure(configuration => { /* * Remove this setting to use the default behavior of Fluent Security, * or modify the internals of Core/Policies/DenyAccessPolicyViolationHandler.cs to * define your desired behavior. */ configuration.DefaultPolicyViolationHandlerIs(() => new DenyAccessPolicyViolationHandler()); /* * Let Fluent Security know how to get the authentication status of the current user */ configuration.GetAuthenticationStatusFrom(() => SecurityProvider.UserIsAuthenticated()); /* * Let Fluent Security know how to get the roles for the current user. * * Complete Core/Policies/DenyAccessPolicyViolationHandler.cs to provide access to your * credentials store */ configuration.GetRolesFrom(() => SecurityProvider.GetCurrentUserRoles()); // Secure all action methods of all controllers configuration.ForAllControllers().DenyAnonymousAccess(); /* * This is where you set up the policies you want Fluent Security to enforce: */ configuration.For<ErrorsController>().Ignore(); configuration.For<Elmah.Mvc.ElmahController>().RequireAnyRole("Super User"); /* * This is an example of a custom policy. Using the policy suggested here: http://www.fluentsecurity.net/wiki/Policies, * we can make the ELMAH controller available only when running under localhost. * * See Core/Policies/LocalOnlyPolicy.cs */ configuration.For<Elmah.Mvc.ElmahController>().AddPolicy<LocalOnlyPolicy>(); configuration.For<HomeController>().Ignore(); configuration.For<HomeController>(ac => ac.Restricted()).RequireAnyRole("Super User"); configuration.For<AccountController>(ac => ac.LogIn(string.Empty)).Ignore(); configuration.For<AccountController>(ac => ac.ResetPassword()).Ignore(); configuration.For<AccountController>(ac => ac.UpdatePassword(string.Empty, string.Empty)).Ignore(); /* * Area config, using ISecurityProfile implementations and the ProfileScanner * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ configuration.Scan(scan => { scan.AssembliesFromApplicationBaseDirectory(); scan.LookForProfiles(); }); }); }
public static ISecurityConfiguration SetupFluentSecurity() { SecurityConfigurator.Configure(configuration => { // Tell FluentSecurity where to obtain the user authentication status from configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated); //configuration.ForAllControllers().DenyAnonymousAccess(); configuration.ForAllControllers().Ignore(); configuration.Advanced.IgnoreMissingConfiguration(); configuration.For <HomeController>(x => x.About()).DenyAnonymousAccess(); configuration.For <HomeController>(x => x.AnonymouslyVisible()).Ignore(); configuration.For <SGAccountController>(x => x.Index()).Ignore(); configuration.For <SGAccountController>(x => x.Login()).Ignore(); ////first deny access to all users except Administrators configuration.ForAllControllersInNamespaceContainingType <DashboardController>() .DenyAuthenticatedAccess() .RequireAnyRole(RoleName.SecurityGuard); // Make sure that users can still log on //configuration.For<AccountController>(ac => ac.LogOn()).Ignore(); //configuration.For<AccountController>(ac => ac.ChangePassword()).RequireAnyRole("Administrator"); //configuration.For<AccountController>(ac => ac.Register()).Ignore(); //configuration.For<AccountController>(ac => ac.Register(null)).Ignore(); }); return(SecurityConfiguration.Current); }
public void Should_create_security_context_from_external_ioc() { // Arrange const bool status = true; var roles = new object[4]; var iocContext = TestDataFactory.CreateSecurityContext(status, roles); FakeIoC.GetAllInstancesProvider = () => new List <ISecurityContext> { iocContext }; SecurityConfigurator.Configure(c => { c.ResolveServicesUsing(FakeIoC.GetAllInstances); }); // Act var context = SecurityContext.Current; // Assert Assert.That(context.CurrenUserAuthenticated(), Is.EqualTo(status)); Assert.That(context.CurrenUserRoles(), Is.EqualTo(roles)); Assert.AreSame(context, iocContext); }
public void Should_resolve_policy_violation_handler_for_exception_from_container() { // Arrange var expectedActionResult = new ViewResult { ViewName = "SomeViewName" }; var violationHandler = new DenyAnonymousAccessPolicyViolationHandler(expectedActionResult); FakeIoC.GetAllInstancesProvider = () => new List <IPolicyViolationHandler> { violationHandler }; SecurityConfigurator.Configure(policy => { policy.ResolveServicesUsing(FakeIoC.GetAllInstances); policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse); policy.For <BlogController>(x => x.Index()).DenyAnonymousAccess(); }); var securityHandler = new SecurityHandler(); // Act var result = securityHandler.HandleSecurityFor(NameHelper.Controller <BlogController>(), "Index", SecurityContext.Current); // Assert Assert.That(result, Is.EqualTo(expectedActionResult)); }
public void Should_throw() { // Arrange Action <ConfigurationExpression> configurationExpression = null; // Act & assert Assert.Throws <ArgumentNullException>(() => SecurityConfigurator.Configure(configurationExpression)); }
public void Should_throw_when_no_authentication_status_mechanism_has_been_provided() { // Arrange SecurityConfigurator.Configure(configuration => {}); var serviceLocator = new ServiceLocator(); // Act & assert Assert.Throws <ConfigurationErrorsException>(() => serviceLocator.Resolve <ISecurityContext>()); }
public void Should_return_current_configuration() { // Act var configuration = SecurityConfigurator.Configure(_configurationExpression); // Assert Assert.That(configuration, Is.Not.Null); Assert.That(configuration, Is.EqualTo(SecurityConfiguration.Current)); }
public void Execute() { SecurityConfigurator.Configure(configuration => { configuration.ResolveServicesUsing(type => { var results = new List <object>(); if (type == typeof(IPolicyViolationHandler)) { results.Add(new DefaultPolicyViolationHandler()); } return(results); }); // Let Fluent Security know how to get the authentication status of the current user configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated); //configuration.GetAuthenticationStatusFrom(() => false); //configuration.GetRolesFrom(Helpers.SecurityHelper.UserRoles); // Let Fluent Security know how to get the roles for the current user configuration.GetRolesFrom(() => { var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { var authTicket = FormsAuthentication.Decrypt(authCookie.Value); //return authTicket.UserData.Split(','); var x = SecurityHelper.Test(); return(x); } else { return(new[] { "" }); } }); // This is where you set up the policies you want Fluent Security to enforce //configuration.For<HomeController>().DenyAnonymousAccess(); configuration.For <HomeController>().Ignore(); configuration.For <AccountController>(ac => ac.LogOn()).DenyAnonymousAccess(); //configuration.For<AccountController>(ac => ac.LogOff()).DenyAnonymousAccess(); //configuration.For<VendorController>(ac => ac.Index()).RequireRole("Vendor"); //configuration.For<AccountController>().DenyAuthenticatedAccess(); //configuration.For<AccountController>(x => x.LogOff()).DenyAnonymousAccess(); //configuration.For<HomeController>().DenyAuthenticatedAccess(); //configuration.For<AccountController>().DenyAnonymousAccess(); //configuration.For<AccountController>(ac => ac.LogOn()).RequireRole(UserRole.Administrator); //configuration.For<AccountController>(ac => ac.LogOn()).DenyAnonymousAccess(); }); //GlobalFilters.Filters.Add(new HandleSecurityAttribute(), 0); }
public static ISecurityConfiguration CreateEmptySecurityConfiguration() { SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(() => false); configuration.IgnoreMissingConfiguration(); }); return(SecurityConfiguration.Current); }
public void Should_verify_expectations_for_void_action_using_convention_expectations() { SecurityConfigurator.Configure(configuration => configuration.For <SampleController>().DenyAnonymousAccess()); var policyExpectations = new PolicyExpectations(); policyExpectations.For <SampleController>().Has <DenyAnonymousAccessPolicy>(); var results = policyExpectations.VerifyAll(SecurityConfiguration.Current); Assert.That(results.Valid(), results.ErrorMessages()); }
public void Should_have_SecurityHandler_set() { SecurityConfigurator.Configure(config => config.GetAuthenticationStatusFrom(() => true)); // Act var attribute = new HandleSecurityAttribute(); // Assert Assert.That(attribute.Handler, Is.TypeOf <SecurityHandler>()); }
protected void Application_Start() { //ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(UnityInstance.Container)); DependencyResolver.SetResolver(new UnityDependencyResolver(UnityInstance.Container)); ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); SetupEnvironment(); Bootstrapper.Initialise(); SecurityConfigurator.Configure( configuration => { // http://www.fluentsecurity.net/getting-started // Let Fluent Security know how to get the authentication status of the current user configuration.GetAuthenticationStatusFrom(() => UserSession.IsAuthenticated); configuration.ResolveServicesUsing(type => UnityInstance.Container.ResolveAll(type)); // This is where you set up the policies you want Fluent Security to enforce on your controllers and actions configuration.ForAllControllers().DenyAnonymousAccess(); configuration.For <PublicController>().Ignore(); configuration.For <AccountController>().Ignore(); configuration.For <VoterAccountController>().Ignore(); configuration.For <AfterController>().AddPolicy(new RequireElectionPolicy()); configuration.For <BallotsController>().AddPolicy(new RequireElectionPolicy()); //configuration.For<BallotsController>().AddPolicy(new RequireLocationPolicy()); configuration.For <BeforeController>().AddPolicy(new RequireElectionPolicy()); configuration.For <DashboardController>().DenyAnonymousAccess(); configuration.For <ElectionsController>().DenyAnonymousAccess(); configuration.For <PeopleController>().AddPolicy(new RequireElectionPolicy()); configuration.For <SetupController>().AddPolicy(new RequireElectionPolicy()); configuration.For <SetupController>(x => x.Upload()).AddPolicy(new RequireElectionPolicy()); //configuration.For<AccountController>(x => x.LogOn()).DenyAuthenticatedAccess(); //configuration.For<AccountController>(x => x.Register()).DenyAuthenticatedAccess(); configuration.For <AccountController>(x => x.ChangePassword()).DenyAnonymousAccess(); }); RegisterGlobalFilters(GlobalFilters.Filters); RegisterGeneralRoutes(RouteTable.Routes); }
public void Should_have_SecurityHandler_set() { SecurityConfigurator.Configure(config => {}); // Act var attribute = new HandleSecurityAttribute(); // Assert Assert.That(attribute.SecurityHandler, Is.AssignableTo(typeof(ISecurityHandler))); Assert.That(attribute.SecurityHandler, Is.Not.Null); }
public void SetUp() { // Arrange SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(() => true); }); // Act _serviceLocator = new ServiceLocator(); }
public void Should_return_null_when_no_policy_is_returned_by_service_locator() { // Arrange SecurityConfigurator.Configure(configuration => configuration.ResolveServicesUsing(t => Enumerable.Empty <object>())); var lazySecurityPolicy = new LazySecurityPolicy <PolicyWithConstructorArguments>(); // Act var policy = lazySecurityPolicy.Load(); // Assert Assert.That(policy, Is.Null); }
public void Should_not_scan_for_eventlistners() { // Arrange SecurityDoctor.Reset(); SecurityDoctor.Current.ScanForEventListenersOnConfigure = false; // Act SecurityConfigurator.Configure(configuration => {}); // Assert Assert.That(SecurityDoctor.Current.ScannedForEventListeners, Is.False); }
public void Should_return_null_when_loading_policy_with_constructor_arguments() { // Arrange SecurityConfigurator.Configure(configuration => {}); var lazySecurityPolicy = new LazySecurityPolicy <PolicyWithConstructorArguments>(); // Act var policy = lazySecurityPolicy.Load(); // Assert Assert.That(policy, Is.Null); }
public void Should_handle_loading_policy_with_empty_constructor_based_on_SecurityPolicyBase() { // Arrange SecurityConfigurator.Configure(configuraiton => {}); var lazySecurityPolicy = new LazySecurityPolicy <PolicyWithBaseClass>(); // Act var policy = lazySecurityPolicy.Load(); // Assert Assert.That(policy, Is.TypeOf <PolicyWithBaseClass>()); }
public void Should_throw_when_context_can_not_be_created_or_resolved() { // Arrange SecurityConfigurator.Configure(configuration => {}); var policy = new Policy <ContextWithConstructorArgs>(); var context = new MockSecurityContext(); // Act & assert var exception = Assert.Throws <ArgumentException>(() => policy.Enforce(context)); Assert.That(exception.Message, Is.EqualTo("The generic argument ContextWithConstructorArgs could not be created or resolved from the container.")); }
public void SetUp() { _securityContext = new MockSecurityContext(); FakeIoC.GetAllInstancesProvider = () => new List <object> { _securityContext }; SecurityConfigurator.Configure(configuration => { configuration.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue); configuration.ResolveServicesUsing(FakeIoC.GetAllInstances); }); }
public void Should_not_throw_when_when_controllername_is_Blog_and_actionname_is_Index() { // Arrange SecurityConfigurator.Configure(policy => { policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsTrue); policy.For <BlogController>(x => x.Index()).DenyAnonymousAccess(); }); var securityHandler = new SecurityHandler(); // Assert Assert.DoesNotThrow(() => securityHandler.HandleSecurityFor(NameHelper.Controller <BlogController>(), "Index", SecurityContext.Current)); }
public void Should_create_context_with_security_context_as_the_only_contructor_argument() { // Arrange FakeIoC.GetAllInstancesProvider = () => new List <ISecurityContext>(); SecurityConfigurator.Configure(configuration => configuration.ResolveServicesUsing(FakeIoC.GetAllInstances)); var policy = new Policy <ContextWithContextConstructor>(); var context = new MockSecurityContext(); // Act policy.Enforce(context); // Assert Assert.That(policy.WasCalledWithCustomContext, Is.True); }
public void Should_load_and_enforce_policy_with_success_result() { // Arrange SecurityConfigurator.Configure(configuraiton => {}); var lazySecurityPolicy = new LazySecurityPolicy <PolicyWithBaseClass>(); var context = new MockSecurityContext(isAuthenticated: true); // Act var result = lazySecurityPolicy.Enforce(context); // Assert Assert.That(result.PolicyType, Is.EqualTo(typeof(PolicyWithBaseClass))); Assert.That(result.ViolationOccured, Is.False); }