Blog

Filter posts by Category Or Tag of the Blog section!

Using FluentSecurity in MVC

Monday, 10 December 2012

FluentSecurity is a nice library which helps you make your Asp.net MVC application more secure with code-base configuration and in one place. By using this library you don't need [Authorize] attribute anymore and also it makes it easier to write unit tests. Go to the Nuget package manager and install the latest version and get started.

 

public class FluentSecurityConfig
{
        public static void Configure()
        {
            SecurityConfigurator.Configure(configuration =>
            {
                configuration.ForAllControllers().DenyAnonymousAccess()
                configuration.For<HomeController>().AllowAny(); 
                configuration.For<AccountController>().Ignore();
                configuration.For<AccountController>(ac => ac.CaptchaImage()).Ignore();
         }
}


And don't forget to let fluent security to handle the authorization in your application, in order to do this add the following configuration to FilterConfig in App_start:

 

public class FilterConfig

    {

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)

        {

            filters.Add(new HandleErrorAttribute());

 

            //Fluent Security configuration

            //To let FluentSecurity handle authorization globally within the application

            //It is important to set the attribute's filter run order to 0 so that FluentSecurity can enforce security rules before anything else in the request pipeline is executed.

           filters.Add(new HandleSecurityAttribute(), 0);

        }

    }

 

And don't forget to register the fluent security configuration in Global.Asax:

 

 public static class StartupConfig
    {
        public static void Start()
        {
            MapperStartupTask.Run(); 
            ViewEngineConfig.Config();
            FluentSecurityConfig.ConfigureFluentSecurity();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            GlobalConfiguration.Configuration.EnsureInitialized();
            BundleConfig.RegisterScriptBundles(BundleTable.Bundles);
            BundleConfig.RegisterStyleBundles(BundleTable.Bundles);
        }
    }

 

Note that you can use the following config to ignore wherever you don't need any security in your application:

 

configuration.IgnoreMissingConfiguration();

 

comments powered by Disqus