Click here to Skip to main content
11,920,211 members (49,163 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


28 bookmarked

Rule Based Security using Microsoft Enterprise Library and CAS

, 7 Nov 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article I’ll explain a solution to secure web applications using custom membership and role providers with the Enterprise Library Security Application Block and code access security.


Rule based security is a very effective way to authorize your code, and code access security is a clean, easy to use and effective way to handle the security validation.

The Enterprise Library Security Application Block provides a configurable way to handle Rule based security.

In this article I’ll explain a solution to secure web applications using custom membership and role providers with the Enterprise Library Security Application Block and code access security.

You need the Enterprise Library installed.

Using the Code

First, we need to implement our custom membership provider, in this example I’ll just use static code to explain the provider (not going to the database or anything).

For this sample I just need to implement the following method:

public override bool ValidateUser(string username, string password)
            return true;

Then, we need to implement our custom role provider.

I just need the following to implement methods:

public override string[] GetRolesForUser(string username)
            return SecurityProvider.GetRolesForUser(username);}
public override bool IsUserInRole(string username, string roleName)
            return SecurityProvider.IsUserInRule(HttpContext.Current.User, roleName);}

Sure, you can build your own providers with a custom database.

Now, Let’s have a look on the [SecurityProvider] class:

public class SecurityProvider{
        public static bool IsUserInRule(IPrincipal principal, string ruleName)
            IAuthorizationProvider authorizationProvider = 
            return authorizationProvider.Authorize(principal, ruleName);
        public static string[] GetRolesForUser(string username)
            switch (username.ToLower())
                case ("admin"):
                    return new string[] { "Admin" };
                case ("manager"):
                    return new string[] { "Manager" };
                case ("user"):
                    return new string[] { "User" };
                    return new string[] { "" };

I use the Enterprise Library Security Application Block to make the validation on the rules from the configuration file.

Then, we need to implement a custom CAS permission and attribute like the following (not implemented functions removed from the next code section but is available in the source code).

public class RulesSecurityPermission : IPermission
        private string _rule;
        public string Rule
                return this._rule;
                this._rule = value;
        public RulesSecurityPermission(string roleName)
            _rule = roleName;
        void IPermission.Demand()
            if (!SecurityProvider.IsUserInRule(Thread.CurrentPrincipal, Rule))
                throw new SecurityException();
public class RulesSecurityPermissionAttribute : CodeAccessSecurityAttribute
        public RulesSecurityPermissionAttribute(SecurityAction action)
            : base(action)
        public override IPermission CreatePermission()
            return new RulesSecurityPermission(Rule);
        private string _role;
        public string Rule
                return this._role;
                this._role = value;

Now, let’s have a look on the configurations file:

    <section name="securityConfiguration" 
       Microsoft.Practices.EnterpriseLibrary.Security, Version=,
       Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  <securityConfiguration defaultAuthorizationInstance="RuleProvider"
      <add type="Microsoft.Practices.EnterpriseLibrary.Security.AuthorizationRuleProvider, 
        Microsoft.Practices.EnterpriseLibrary.Security, Version=,
        Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        <add expression="R:Admin" name="Administratoin" />
        <add expression="R:Admin OR R:Manager" name="Management" />
        <add expression="R:Manager OR R:User" name="Usage" />


  <compilation debug="true" />

  <authentication mode="Forms">
    <forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx">

    <deny users="?"/>

  <membership defaultProvider="CustomMembershipProvider">
      <add name="CustomMembershipProvider"

  <roleManager defaultProvider="CustomRolesProvider" enabled="true">
      <add name="CustomRolesProvider"
        type="Shokr.Security.RuleBasedSecurity.CustomRolesProvider" />


In the above code, I had registered the [AuthorizationRuleProvider] from the Enterprise Library and configured our custom membership and roles providers.

Finally, this is the sample in action:

Navigate to the login page, and login with [admin] and any password.


You will be redirected to the default page:


Click on [Administrative function], you will see that the method executed successfully


Click on [User function], you will see security error:


Points of Interest

  • Code access security is a very nice way to secure your code.
  • Enterprise library provides a rich configurable way to handle rule based security.
  • With the implementation of custom permission and attribute, you can use the given sample to find other ways to secure your applications.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ahmed Shokr
Architect INC Technologies
Kuwait Kuwait
+7 years of experience in designing and implementing Microsoft Based Solutions.
+5 years of experience in SharePoint implementations from MCMS 2002 to the latest version.
+3 years of experience as presales and technology advisory.
Strong analytic, design and client facing skills.
Strong record in consultation and presales with associated Gulf business understanding and market analysis.
Worked closely with Microsoft Kuwait & Qatar Offices SSPs, PTAs, PAMs and SAMs.
Extensive experience in BizTalk Server 2009, SSAS, PerformancePoint Services and Excel Services.
Active member in the Virtual Technology Specialist and Customer Immersion Experience programs.
Strong record in team leading and projects supervision.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 4 Pin
Ehsan yazdani rad9-Oct-14 0:49
memberEhsan yazdani rad9-Oct-14 0:49 
GeneralMy vote of 3 Pin
santoshkumarbehera7-Feb-11 21:27
membersantoshkumarbehera7-Feb-11 21:27 
GeneralMy vote of 1 Pin
mwdiablo23-Apr-09 15:14
membermwdiablo23-Apr-09 15:14 
Generalerror when running the example provided Pin
Member 192629415-Feb-09 6:16
memberMember 192629415-Feb-09 6:16 
GeneralRe: error when running the example provided Pin
Member 192629415-Feb-09 6:37
memberMember 192629415-Feb-09 6:37 
Generalgood article Pin
Donsw7-Feb-09 14:09
memberDonsw7-Feb-09 14:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151120.1 | Last Updated 7 Nov 2008
Article Copyright 2008 by Ahmed Shokr
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid