Programmer to ProgrammerTM  
Wrox Press Ltd  
   
  Search ASPToday Living Book ASPToday Living Book
Index Full Text
  cyscape.com

ASPToday Home
 
 
Home HOME
Site Map SITE MAP
Index INDEX
Full-text search SEARCH
Forum FORUM
Feedback FEEDBACK
Advertise with us ADVERTISE
Subscribe SUBSCRIBE
Bullet LOG OFF
                         
      The ASPToday Article
June 27, 2002
      Previous article -
June 26, 2002
   
 
   
   
   
ASP.Net Custom Role-Based Authorization   Terry Mitchell  
by Terry Mitchell
 
CATEGORIES:  .NET Framework, Security/Admin  
ARTICLE TYPE: Overview Reader Comments
   
    ABSTRACT  
 

The majority of web applications require some form of user authentication and authorization. This can range from simply restricting part of an application to members only, through to sophisticated management of content according to the type of user. One of the most useful features of ASP.NET is the integration of a generic user authentication and authorization framework that can be molded to the requirements of most applications. The framework makes it simple to incorporate authentication, and control access to content, based on the roles of users. This article demonstrates the creation of security principal and identity objects for use in form–based authentication using a custom data source, and implementation of role–based authorization to restrict content to users that are members of a specified role.




   
                   
    Article Discussion   Rate this article   Related Links   Index Entries  
   
 
    ARTICLE

Introduction

As applications become increasingly more sophisticated it is a common requirement to have some form of role-based authorization, so that some application content and functionality is restricted to specific types of users, such as administrators of an application.

The ASP.NET Framework includes security providers for use with Basic, Digest and Integrated Windows authentication, Microsoft Passport authentication and custom form-based authentication. Srinivasa Sivakumar discusses these authentication options in the ASPToday articles ASP.NET Authentication Options - Part 1 and ASP.NET Authentication Options - Part 2.

Currently, the most widely used method for securing web applications is form-based authentication against a custom user data source. The focus of this article and sample application is how to achieve role-based authorization with custom user data by using the Forms Authentication Provider and the ASP.NET security framework.

System Requirements

The sample application was developed with Visual Studio.NET and requires Internet Information Server 5.0 and the .NET Framework to run. This article assumes the reader has basic knowledge of XML, C#, the .NET Framework and ASP.NET development.

The Sample Application

For simple scenarios, role-based authorization can be implemented with a minimal amount of coding by storing the user and role data in the credentials section of the web.config file. Access to files and folders can then be restricted based on user name or roles by configuring authorization sections. All that needs to be developed is a login page that makes a call to the Forms Authentication Provider to authenticate users. Examples of this can be found in the ASP.NET QuickStart Tutorials (http://www.gotdotnet.com/quickstart/aspplus/?WROXEMPTOKEN=476571ZcMoJqXaJL70NGbOglSJ) under the Security menu item , and in the MSDN library documentation of the Forms Authentication Provider (http://msdn.microsoft.com/library/en-us/cpguide/html/cpconthecookieauthenticationprovider.asp?WROXEMPTOKEN=476571ZcMoJqXaJL70NGbOglSJ).

While storing user data in the web.config file may be suitable for simple sites, more complex n-tier applications will typically require user data to be stored in an external database, such as Microsoft SQL Server or a host of other alternatives. To integrate a custom user data source into the forms authentication framework, without loosing the ability to control access to application content using the authorization settings in the web.config file, custom user context objects must be created to replace the default user context objects used by the framework at the appropriate stage of the authentication process.

The sample application demonstrates the implementation of custom user context objects that contain user and role information loaded from a custom data source, and the integration of these objects into the ASP.NET authentication and authorization framework. It also includes examples of how to configure an application so that some files or folders are restricted to users in a specific role, and finally it shows how to access the properties and roles of the logged in user in code.

The User Data

Because database access is not the focus of this article, the user data for the example is contained in an XML file. This has been done purely to simplify the example, by avoiding the complication of setting up and connecting to a database. It should be noted that in a real world scenario, an XML file does not provide sufficient security for storing user data, and a more secure data source, such as Microsoft SQL Server should be used instead. The example code for reading user data can be easily modified to read from other data sources.

The XML file is structured with a root 'users' element, which can contain multiple 'user' elements. Each user element contains the following attributes:

The user element can optionally contain a 'roles' element, which in turn can contain multiple 'role' elements. The role element contains a 'name' attribute, which specifies the name of a role that the user is a member of.

Example User XML

The user data for the example is shown below.

<?xml version="1.0" encoding="utf-8" ?>
<users>
  <user name="bob" pass="bob" firstName="Bob" lastName="Smith">
    <roles>
      <role name="admin"></role>
    </roles>
  </user>
  <user name="jim" pass="jim" firstName="Jim" lastName="Brown"></user>  
</users>

The example defines two users - Bob and Jim. Bob is a member of the ' admin ' role and thus will be able to access content and perform actions restricted to administrators of the application. Jim is not a member of any roles, so while he will be able to access the members area of the application, he will not be able to access anything that is restricted to administrators.

User Context Objects

The ASP.NET security framework uses objects that implement the System.Security.Principal.IPrincipal and System.Security.Principal.IIdentity interfaces. The IPrincipal interface is implemented by objects that represent the security context of the user on whose behalf an application is running. The IPrincipal object contains the identity of the user in an object which implements the IIdentity interface.

When a user is successfully authenticated using the forms authentication, the default behavior of the framework is to create objects of type System.Security.Principal.GenericPrincipal and System.Web.Security.FormsIdentity for the user and place these in the HttpContext of the current request.

To integrate custom user data into the Forms Authentication Provider, the GenericPrincipal and FormsIdentity objects need to be replaced during the authentication process with custom implementations of the IPrincipal and IIdentity interfaces, which can contain the user and role information defined in the data. The definition of these objects is shown below.

CustomIdentity

The CustomIdentity class is an implementation of the IIdentity interface, which requires the following properties to be included:

In addition to these required members, the class also contains FirstName and LastName properties, which have been included to support the attributes of the user XML element. A StringCollection property called Roles has also been added. This will contain a list of all the roles that the user is a member of.

using System;
using System.Collections.Specialized;
using System.Security.Principal;
using System.Xml;

namespace CustomAuthSample
{
    public class CustomIdentity : IIdentity
    {
        private bool _bIsAuthenticated;
        private string _sAuthenticationType;
        private string _sUserName;
        private string _sFirstName;
        private string _sLastName;
        private StringCollection _lstRoles = new StringCollection();

        public CustomIdentity(string sUserName, bool bIsAuthenticated, string sAuthenticationType)
        {
            _sUserName = sUserName;
            _bIsAuthenticated = bIsAuthenticated;
            _sAuthenticationType = sAuthenticationType;            
        }

        /// <summary>
        /// The type of authentication used.
        /// </summary>
        public string AuthenticationType    //Required by IIdentity
        {
            get    { return _sAuthenticationType; }
        }

        /// <summary>
        /// Indicates whether user has been authenticated.
        /// </summary>
        public bool IsAuthenticated    //Required by IIdentity
        {
            get    { return _bIsAuthenticated;    }
        }

        /// <summary>
        /// The unique name of the user.
        /// </summary>
        public string Name    //Required by IIdentity
        {
            get    { return _sUserName; }
        }

        /// <summary>
        /// The user's last name.
        /// </summary>
        public string FirstName    //For the 'firstName' attribute.
        {
            get    { return _sFirstName; }
            set { _sFirstName = value; }
        }

        /// <summary>
        /// The user's first name.
        /// </summary>
        public string LastName    //For the 'lastName' attribute.
        {
            get    { return _sLastName; }
            set { _sLastName = value; }
        }
        
        /// <summary>
        /// A list of roles the user is a member of.
        /// </summary>
        public StringCollection Roles    //For the 'role' elements.
        {
            get { return _lstRoles; }
        }
    }
}

CustomPrincipal

The CustomPrincipal class implements the IPrincipal interface, so the Identity property and the IsInRole method are required. The Identity property returns an object of type IIdentity, which in this case will be an instance of the CustomIdentity class. The security framework uses the IsInRole method to check for role membership during authorization. The IsInRole method can also be accessed from application code to perform role membership checks as required.

using System;
using System.Security.Principal;

namespace CustomAuthSample
{
    public class CustomPrincipal : IPrincipal
    {
        private CustomIdentity _cidIdentity;

        /// <summary>
        /// Constructs an instance of the CustomPrincipal class using the supplied CustomIdentity.
        /// </summary>
        /// <param name="cidIdentity"></param>
        public CustomPrincipal(CustomIdentity cidIdentity)
        {
            _cidIdentity = cidIdentity;
        }

        /// <summary>
        /// Returns the CustomIdentity contained by this CustomPrincipal.
        /// </summary>
        public IIdentity Identity    //Required by IPrincipal
        {
            get    { return _cidIdentity; }
        }

        /// <summary>
        /// Checks if the user is a member of a role.
        /// </summary>
        /// <param name="sRole">The name of the role to check for membership of.</param>
        /// <returns>true if the user is a member of the role, otherwise false.</returns>
        public bool IsInRole(string sRole)    //Required by IPrincipal
        {
            return _cidIdentity.Roles.Contains(sRole);
        }        
    }
}

Authentication Component

Next we require a way to authenticate user credentials and create CustomPrincipal and CustomIdentity objects once authentication has occurred. In the sample application this functionality is encapsulated in the SecurityManager class.

SecurityManager

The SecurityManager class has two methods - Authenticate and ConstructCustomPrincipal. Both of these methods read from the user XML file described previously.

The purpose of the Authenticate method is to check the validity of a username and password. Role membership is not taken into account in this method. The Authenticate method takes a username and password as parameters and performs a check of these credentials against the user XML data, returning true if a match is found or false if not.

The ConstructCustomPrincipal method creates and returns a CustomPrincipal object and the associated CustomIdentity object constructed from the user XML element with a name that matches the Name property of the supplied IIdentity object. After the properties of the CustomIdentity are set from the name, firstName and lastName attributes in the user element, the Roles collection is populated with the names of any role elements contained within the user element. The CustomPrincipal object returned by this method will be used to replace the default GenericPrincipal object created by the FormsAuthenticationModule.

using System;
using System.Xml;
using System.Security.Principal;

namespace CustomAuthSample
{
    public class SecurityManager
    {
        private string _sUsersPath;//Stores path to user data XML file.

        /// <summary>
        /// Initializes a new instance of the SecurityManager class.
        /// </summary>
        /// <param name="sUsersPath">The path to the user XML file</param>
        public SecurityManager(string sUsersPath)
        {
            this._sUsersPath = sUsersPath; //store the path of the user data 
                                           //XML file in a member variable.
        }

        /// <summary>
        /// Authenticates a username and password.
        /// </summary>
        /// <param name="sUserName">The username. Case insensitive.</param>
        /// <param name="sPassword">The password. Case sensitive.</param>
        /// <returns>true if sUserName and and sPassword are authenticated, 
        /// otherwise false.</returns>

        public bool Authenticate(string sUserName, string sPassword)
        {
            XmlDocument xdocUsers = new XmlDocument();
            xdocUsers.Load(_sUsersPath); //Load the user data XML file.
            bool bAuthenticated = false; //Initialise the return value to false - not authenticated.
            //Loop through the 'user' XmlElements
            foreach(XmlElement xelUser in xdocUsers.DocumentElement.ChildNodes)
            {
                //look for 'user' XmlElement with matching username & password.
                if(xelUser.GetAttribute("name").ToUpper() == sUserName.ToUpper()
                        && xelUser.GetAttribute("pass") == sPassword)
                {
                    //Username and password authenticated.
                    bAuthenticated = true; break;
                }
            }
            return bAuthenticated;
        }

        /// <summary>
        /// Constructs an instance a CustomPrincipal object from a supplied IIdentity.
        /// </summary>
        /// <param name="idIdentity">The IIdentity object containing user information.</param>
        /// <returns>A CustomPrincipal object for the user identified in the 
        /// IIdentity object.</returns>
        public CustomPrincipal ConstructCustomPrincipal(IIdentity idIdentity)
        {
            XmlDocument xdocUsers = new XmlDocument();
            xdocUsers.Load(_sUsersPath); //Load the user data XML file.
            XmlElement xelUserMatch = null; //Variable to store the matching 'user' XML element.
            //Loop through the 'user' XmlElements
            foreach(XmlElement xelUser in xdocUsers.DocumentElement)
            {
                //look for 'user' XmlElement with name attribute matching idIdentity.Name property.
                if(xelUser.GetAttribute("name").ToUpper() == idIdentity.Name.ToUpper())
                {
                    //found a match, set the xelUserMatch variable.
                    xelUserMatch = xelUser; break;
                }
            }
            if(xelUserMatch != null)
            {
                //Construct a CustomIdentity for the user with the name 
                //attribute from the 'user' element, and the IsAuthenticated 
                //and AuthenticationType properties of the supplied IIdentity parameter.
                CustomIdentity cidIdentity = new CustomIdentity(xelUserMatch.GetAttribute("name"),
                    idIdentity.IsAuthenticated, idIdentity.AuthenticationType);
                //Set FirstName and LastName properties from the attributes of the 'user' element.
                cidIdentity.FirstName = xelUserMatch.GetAttribute("firstName");
                cidIdentity.LastName = xelUserMatch.GetAttribute("lastName");
                //Look for a child 'roles' element in the 'user' element.
                if(xelUserMatch.HasChildNodes)
                {
                    XmlElement xelRoles = null;
                    foreach(XmlElement xelChild in xelUserMatch.ChildNodes)
                    {
                        if(xelChild.Name == "roles")
                        {
                            xelRoles = xelChild;
                        }
                    }
                    if(xelRoles != null)
                    {
                        //Found a roles element. Loop through each child of the 'roles' element
                        //and add the value of the 'name' attribute to the 
                        //Roles collection in the CustomIdentity.
                        foreach(XmlElement xelRole in xelRoles.ChildNodes)
                        {
                            cidIdentity.Roles.Add(xelRole.GetAttribute("name"));
                        }
                    }
                }
                //Create and return a CustomPrincipal object constructed with the CustomIdentity object. 
                CustomPrincipal cprPrincipal = new CustomPrincipal(cidIdentity);
                return cprPrincipal;
            }
            else
            {
                return null;
            }      
        }
    }
}

Authentication Process

To facilitate authentication, a login WebForm is required for collection and verification of the username and password. Some code also needs to be added to the Application_AuthenticateRequest method in the Global.asax.cs file in order to integrate the CustomPrincipal and CustomIdentity objects into the authentication framework.

Login Page

The HTML for the login form as contained in Login.aspx is shown below. The form consists of fields for entering the username and password and a submit button. In order to simplify the code for this example, validation of the fields is not included.

...
<body>
  <form id="Login" method="post" runat="server">
    <table>
      <tr>
        <td>Username</td>
        <td>
        <asp:TextBox id="_txtUserName" runat="server"></asp:TextBox>
        </td>
      </tr>
      <tr>
        <td>Password</td>
        <td>
         <asp:TextBox id="_txtPassword" runat="server" TextMode="Password"></asp:TextBox>
       </td>
     </tr>
     <tr>
       <td></td>
       <td align="right">
       <asp:Button id="_btnLogin" runat="server" Text="Login"></asp:Button>
       </td>
      </tr>
    </table>
  </form>
</body>
...

Login Event Handler

Next, an event handler is required for when the Login button is clicked. The event handler creates an instance of the SecurityManager class, passing the path of the XML file containing the user data into the constructor. Once constructed, the SecurityManager.Authenticate method is called with the username and password values retrieved from the form fields. If the supplied user credentials are valid the FormsAuthentication.RedirectFromLoginPage method is called, which issues an authentication cookie using the supplied username and then redirects the browser to the page that was requested. In this case the cookie is not persistent and will expire when the user closes their browser. If an authentication cookie that persists across multiple browser sessions is required, the second parameter of the RedirectFromLoginPage method must be set to true.

private void _btnLogin_Click(object sender, System.EventArgs e)
{
    //Construct SecurityManager with path to user data XML file.
    SecurityManager smSecurity = new SecurityManager(Server.MapPath("Users.xml"));
    //Retrieve username and password from the form.
    string sUserName = this._txtUserName.Text;
    string sPassword = this._txtPassword.Text;
    //Check username and password.
    bool bAuthenticated = smSecurity.Authenticate(sUserName, sPassword);
    if(bAuthenticated)
    {
        //Userauthenticated. Set authentication ticket and redirect to requested page.
        System.Web.Security.FormsAuthentication.RedirectFromLoginPage(sUserName, false);
    }
}

Changes to Global.asax.cs

The HttpApplication object provides an event called AuthenticateRequest, which is fired when the identity of a user has been established. This event can be handled in the Global.asax.cs file by defining the Application_AuthenticateRequest method. It is in this method that the code for replacing the GenericPrincipal and FormsIdentity objects with CustomPrincipal and CustomIdentity objects must be placed. This is so that when authorization occurs, which happens after the AuthenticateRequest event is fired, the CustomPrincipal object will be used by the framework when perform role membership checks instead of the GenericPrincipal object.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    if(this.User != null)
    {
        //Construct SecurityManager with path to user data XML file.
        SecurityManager smSecurity = new SecurityManager(Server.MapPath("Users.xml"));
        //Create a CustomPrincipal for the current user.
        CustomPrincipal cprPrincipal = 
            smSecurity.ConstructCustomPrincipal(this.User.Identity);
        //Replace the GenericPrincipal in the HttpContext for the current request.
        this.Context.User = cprPrincipal;
    }
}

It is important in the Application_AuthenticateRequest to check that the User property of the HttpContext is not null before accessing it. The AuthenticateRequest event is fired a number of times while a user is being authenticated, and sometimes the User property is null . This is because up to four separate page requests are required to authenticate a user - one for the page the user requests, one for the redirection to the login page, one for the post-back of the login page and finally one for the redirection to the page originally requested after successful authentication. The GenericPrincipal object for the user is only available for the final time AuthenticateRequest is fired when the user is redirected back to the page they requested after authentication. At all other times prior to this the User property of the HttpContext will return null .

Example Content Pages

To demonstrate the configuration of role-based authorization to restrict file access based on the roles of users, three example content pages have been added to the sample application, each requiring a different level of security access. The three content pages and their requirements are as follows:

Configuration Settings

All that is required now to restrict access to the sample pages, as specified, is to add the appropriate settings to the web.config file. Firstly the application is configured to redirect to Login.aspx when authentication is required, by including the authentication tag, setting mode to ' Forms ' and in the child forms tag specifying ' Login.aspx ' as the loginUrl.

Also, location tags that contain the authorization settings for the Member.aspx and Admin.aspx pages are required. If the whole application was to be given the same authorization settings the authorization tag could be included inside the main system.web tag. In this example location tags are required so that different settings can be applied to the specified files. The path attribute in the location tag can specify either a file or a folder to which the contained settings will be applied. An alternative method for specifying the authorization settings for a sub folder is to add another web.config file to the sub folder and include authorization settings in it, which will override the settings of the parent folder.

The authorization settings are configured using allow and deny tags, which are iterated through until the first rule that applies to the current user is found. Both the allow and the deny tags can contain either a users attribute, which specifies a coma-separated list of users to be granted or denied access, or a roles attribute, which specifies a coma-separated list of roles to be granted or denied access. The users attribute can also contain either a question mark ( ?), which matches anonymous users, or an asterisk ( *), which matches all users.

Thus the requirements of the Member.aspx can be met by adding a deny rule to its authorization tag and specifying ' ? ' as the value of the users attribute, which will deny all anonymous users. For Admin.aspx, users in the admin role are given access by adding an allow rule with the roles attribute set to ' admin '. All users that do not satisfy this rule are then denied access by adding a deny rule with the users attribute set to ' * '.

<configuration>
  <system.web>
      <!-- Other configuration settings -->

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

      <!-- Other configuration settings -->
  </system.web>

        <location path="Member.aspx">
          <system.web>
            <authorization>
                <deny users="?"></deny>
            </authorization>
          </system.web>
    </location>
    <location path="Admin.aspx">
          <system.web>
            <authorization>
                   <allow roles="admin"></allow>
                   <deny users="*"></deny>
            </authorization>
          </system.web>
    </location>

</configuration>

Checking Roles In Code

In addition being able to configure the URL authorization settings in the web.config file, it is also useful to be able to access user details and check a user's role membership programmatically. The code below is from the code-behind class for Member.aspx and shows the details of the current user being accessed, and a check for membership of the admin role being performed using two different approaches. The results are written out to a Label Web Control.

The CustomPrincipal and ContextIdentity objects for the current user are accessible via the User property of the Page or UserControl objects, which returns a reference to an IPrincipal. Once these objects are cast to the appropriate types, the details of the user can be read from the CustomIdentity object, and role membership can be checked using the IsInRole method of the CustomPrincipal object.

An alternate way to check role membership is to use a PrincipalPermission object. Correct identity and authorization of the current user can be ensured using a PrincipalPermission object by passing the required username and role information into the object's constructor, and calling the Demand method. The Demand method raises a SecurityException if the user does not have the required permissions.

...
protected System.Web.UI.WebControls.Label _lblUser;

private void Page_Load(object sender, System.EventArgs e)
{
    CustomPrincipal cprUser = this.User as CustomPrincipal;
    if(cprUser != null)
    {
        //Get the CustomIdentiy for the current user and write a 
        //greeting using the FirstName and LastName properties.
        CustomIdentity cidIdentity = cprUser.Identity as CustomIdentity;
        _lblUser.Text = "Hello " + cidIdentity.FirstName + " " + 
cidIdentity.LastName + "<br>"; 

        //Check if the user is in the 'admin' role using IIdentity.IsInRole()
            _lblUser.Text += "<br>Role check with IsInRole():<br>";
        if(cprUser.IsInRole("admin"))
        {
            _lblUser.Text += "You are an administrator.<br>";
        }
        else
        {
            _lblUser.Text += "You are not an administrator.<br>";
        }
        _lblUser.Text += "<br>Role check with PrincipalPermission object:<br>";

        //Perform the same check with PrincipalPermission object that 
        //requires the current user to be in the 'admin' role.
        System.Security.Permissions.PrincipalPermission objPermisson = 
            new System.Security.Permissions.PrincipalPermission(null, "admin", true);
        try
        {
            objPermisson.Demand();  //Throws a SecurityException if not in the correct role.
            _lblUser.Text += "PrincipalPermission.Demand() succeeded. You are an administrator.<br>";
        }
        catch(System.Security.SecurityException ex)
        {    //Demand() failed. Catch the SecurityException and write out a message.
            _lblUser.Text += "PrincipalPermission.Demand() failed. You are not an administrator.<br>"
                + ex.Message;
        }
    }
}
...

More complex permission checks can also be performed by combining two PrincipalPermission objects using their Union or Intersect methods. If two PrincipalPermission object are combined using the Intersect method, the requirements of both the original objects must be satisfied for the call to the Demand method to succeed, whereas if they are combined using the Union method the call to Demand will succeed if either of the original object's requirements are satisfied. Further information about combining PrincipalPermission objects can be found in the MSDN documentation (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcombiningprincipalpermissionobjects.asp&WROXEMPTOKEN=476571ZcMoJqXaJL70NGbOglSJ).

The Application In Action

A menu has been added to the top of each of the sample pages to allow navigation between them. When the Member or Admin pages are requested and the user is not yet authenticated, the user is redirected to the Login.aspx page, as specified by the authorization settings in the web. config file.

Below is a screen shot of Member.aspx after logging in with the credentials for Bob Smith, who is a member of the admin role. When Bob Smith is logged in access is granted to both the Member page and the Admin page. When logged in as Jim Brown, access to the Admin page is denied and if it is requested, the login page is presented instead.

The event handler for the Logout LinkButton on the Member.aspx and Admin.aspx pages calls the FormsAuthentication.SignOut() method to delete the user's authentication cookie, and then redirects back to Default.aspx.

Application Setup

To set up the sample application download and unzip the files into a folder on your machine and then add a virtual directory for the folder in IIS called ' CustomAuthSample '. Load the application by pointing your browser to Default.aspx in the virtual directory.

To open the Visual Studio.NET project, first ensure the CustomAuthSample.csproj.webinfo file contains the correct URL for the project file ( CustomAuthSample.csproj) by opening it in notepad and making any changes required. If the virtual directory is created under the default web site on your machine the URL will be http://localhost/CustomAuthSample/CustomAuthSample.csproj. Then open the project with the Visual Studio.NET Development Environment.

Further Work

While the sample application uses an XML file to store the user and role information, it can be easily modified to use more secure data source such as SQL Server or Active Directory by changing where the Authenticate and ConstructCustomPrincipal methods of the SecuriyManager class obtain their data.

Conclusion

Setting up role-based authorization with custom user data in ASP.NET is a relatively straightforward process, and the result is a highly configurable and flexible solution. As demonstrated by the sample application, the replacement of the default user context objects with custom user context objects allows seamless integration of any user data source with the authentication and authorization framework. Moreover, the ability to access user properties and determine role membership from within any page or user control provides a simple mechanism for further controlling and customizing the content presented to each user. The techniques used in the sample can easily be extended to create more sophisticated role-base security for web applications.

Please rate this article using the form below. By telling us what you like and dislike about it we can tailor our content to meet your needs.

Article Information
Author Terry Mitchell
Chief Technical Editor John R. Chapman
Project Manager Helen Cuthill
Reviewers Neil Piggot, Susan Connery

If you have any questions or comments about this article, please contact the technical editor.

Fast Track Books from Wrox Press
Fast Track ASP.NET is a concise introduction to the concepts and techniques that you will need to grasp in order to start building ASP.NET applications. ASP.NET introduces many new features for web application development. It promises a wealth of benefits including higher performance, pain free multi-device development, and easier code reuse. This book will show you what is possible and give you an understanding of ASP.NET that you will find invaluable as you go on to develop cutting edge applications.

If you want to know what ASP.NET can do and how it should be used in order to help you gain the benefits, Fast Track ASP.NET is the book for you.
Now that the .NET Framework and the Visual Studio .NET IDE have been officially released by Microsoft, it is imperative for developers to get up to speed with the new .NET languages quickly and effectively.

Fast Track VB.NET is the book for this task, helping experienced Visual Basic developers note the key similarities, and differences, between their current language and Visual Basic .NET.
  • An introduction to the .NET Framework, including new IDE and language features
  • New Windows user interface capabilities
  • New object-oriented and web capabilities of Visual Basic .NET
  • Data access using Visual Basic .NET
  • Installation and deployment
  • Interoperability and migration
If you want a C# book that is compact, fast-paced but still provides the quality of information that you have come to expect from a Wrox book - you want Fast Track C#, newly available from Wrox Press.

This book will help you to quickly learn about the following:
  • Understand what C# is, and how it fits into the .NET Framework
  • A concise introduction to all the main features of the C# language, with Java and C++ comparisons noted
  • Using the .NET base classes
  • Writing and deploying Windows applications with C# and Visual Studio .NET
  • Creating and configuring .NET assemblies
  • Accessing databases with ADO.NET, and using XML in C#
  • Integrating your existing COM components with the .NET Framework
  • COM+ Services in the .NET Framework
  • Building web applications with ASP.NET pages
  • Creating web services in C#

 
 
   
  RATE THIS ARTICLE
  Please rate this article (1-5). Was this article...
 
 
Useful? No Yes, Very
 
Innovative? No Yes, Very
 
Informative? No Yes, Very
 
Brief Reader Comments?
Your Name:
(Optional)
 
  USEFUL LINKS
  Related Tasks:
 
 
   
  Related ASPToday Articles
   
  • ASP.NET Authentication Options - Part 2 (May 15, 2001)
  • ASP.NET Authentication Options - Part 1 (May 4, 2001)
  •  
           
     
     
      Related Sources
     
  • PrincipalPermission object documentation in the MSDN library : http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconprincipalpermissionobjects.asp
  • Forms Authentication Module documentation in the MSDN library: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcontheformsauthenticationmodule.asp
  • ASP.Net QuickStart Tutorial : http://www.gotdotnet.com/quickstart/aspplus/
  •  
     
           
      Search the ASPToday Living Book   ASPToday Living Book
     
      Index Full Text Advanced 
     
     
           
      Index Entries in this Article
     
  • allow element
  •  
  • Authenticate method
  •  
  • AuthenticateRequest event
  •  
  • authentication
  •  
  • authentication element
  •  
  • AuthenticationType property
  •  
  • authorization
  •  
  • ConstructCustomPrincipal method
  •  
  • credentials
  •  
  • custom configuration section handler
  •  
  • CustomIdentity class
  •  
  • CustomPrincipal class
  •  
  • Demand method
  •  
  • deny element
  •  
  • event handlers
  •  
  • FirstName property
  •  
  • form validation
  •  
  • Forms Authentication Provider
  •  
  • forms element
  •  
  • FormsAuthentication object
  •  
  • FormsAuthenticationModule class
  •  
  • FormsIdentity class
  •  
  • GenericPrincipal class
  •  
  • HTTPApplication class
  •  
  • HttpContext class
  •  
  • Identity property
  •  
  • IIdentity interface
  •  
  • Intersect method
  •  
  • IPrincipal interface
  •  
  • IsAuthenticated property
  •  
  • IsInRole method
  •  
  • LastName property
  •  
  • location element
  •  
  • login management
  •  
  • login page
  •  
  • loginUrl attribute
  •  
  • mode attribute
  •  
  • Name property
  •  
  • Page Objects
  •  
  • Path attribute
  •  
  • PrincipalPermission class
  •  
  • RedirectFromLoginPage method
  •  
  • role-based authorization with custom user data
  •  
  • role-based security
  •  
  • roles attribute
  •  
  • Roles property
  •  
  • security
  •  
  • SecurityManager class
  •  
  • System.Security.Principal namespace
  •  
  • System.Web.Security namespace
  •  
  • Union method
  •  
  • user data
  •  
  • User property
  •  
  • UserControl class
  •  
  • users attribute
  •  
  • web forms
  •  
  • web.config file
  •  
  • XML file
  •  
     
     
    HOME | SITE MAP | INDEX | SEARCH | REFERENCE | FEEDBACK | ADVERTISE | SUBSCRIBE
    .NET Framework Components Data Access DNA 2000 E-commerce Performance
    Security Admin Site Design Scripting XML/Data Transfer Other Technologies

     
    ASPToday is brought to you by Wrox Press (http://www.asptoday.com/OffSiteRedirect.asp?Advertiser=www.wrox.com/&WROXEMPTOKEN=476571ZcMoJqXaJL70NGbOglSJ). Please see our terms and conditions and privacy policy.
    ASPToday is optimised for Microsoft Internet Explorer 5 browsers.
    Please report any website problems to webmaster@asptoday.com. Copyright © 2002 Wrox Press. All Rights Reserved.