Click here to Skip to main content
6,305,776 members and growing! (15,715 online)
Email Password   helpLost your password?
Web Development » Web Security » Security     Intermediate License: The Code Project Open License (CPOL)

Rule Based Security using Microsoft Enterprise Library and CAS

By Ahmed Shokr

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.
C#, ASP.NET, Dev
Posted:7 Nov 2008
Views:7,026
Bookmarked:20 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
9 votes for this article.
Popularity: 2.62 Rating: 2.75 out of 5
3 votes, 33.3%
1

2
3 votes, 33.3%
3
1 vote, 11.1%
4
2 votes, 22.2%
5

Introduction

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 = 
                AuthorizationFactory.GetAuthorizationProvider();
            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" };
 
                default:
                    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
        {
            get
            {
                return this._rule;
            }
            set
            {
                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
        {
            get
            {
                return this._role;
            }
            set
            {
                this._role = value;
            }
        }
    }

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

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

<system.web>

  <compilation debug="true" />

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

  <authorization>
    <deny users="?"/>
  </authorization>

  <membership defaultProvider="CustomMembershipProvider">
    <providers>
      <clear/>
      <add name="CustomMembershipProvider"
        type="Shokr.Security.RuleBasedSecurity.CustomMembershipProvider"/>
    </providers>
  </membership>

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

  </system.web>
</configuration>

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.

Login.JPG

You will be redirected to the default page:

Main.JPG

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

Admin.JPG

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

User.JPG

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.

License

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

About the Author

Ahmed Shokr


Member
I'm working as .NET Team Leader in Safat Enterprise Solutions in Kuwait city.
I'm working in the MOSS team, we use MOSS 2007, ASP.NET 3.0 and others.
I like working in web applications and playing with Microsoft servers Smile.
Occupation: Team Leader
Company: Safat Enterprise Solutions
Location: Kuwait Kuwait

Other popular Web Security articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmembermwdiablo15:14 23 Apr '09  
Generalerror when running the example provided PinmemberMember 19262946:16 15 Feb '09  
GeneralRe: error when running the example provided PinmemberMember 19262946:37 15 Feb '09  
Generalgood article PinmemberDonsw14:09 7 Feb '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 7 Nov 2008
Editor: Sean Ewington
Copyright 2008 by Ahmed Shokr
Everything else Copyright © CodeProject, 1999-2009
Web11 | Advertise on the Code Project