Click here to Skip to main content
Click here to Skip to main content

Understanding ASP.NET Roles and Membership - A Beginner's Tutorial

, 7 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How ASP.NET lets us create sites with an authentication and authorization mechanism in place and how we can use ASP.NET server controls to quickly and efficiently implement this.

Introduction

How many sites have you seen that requires you to login? I guess the answer to this question is "almost all of them". Well, the idea behind this article is to understand how ASP.NET lets us create sites with an authentication and authorization mechanism in place and how we can use ASP.NET server controls to quickly and efficiently implement this.

Background

When we are working on applications where authentication and authorization is a key requirement, then we will find the ASP.NET roles and membership feature very useful. Authentication means validating users. In this step, we verify user credentials to check whether the person tying to log in is the right one or not. Authorization on the other hand is keeping track of what the current user is allowed to see and what should be hidden from him. It is more like keeping a register to what to show and what not to show to the user.

Whenever a user logs in, he will have to authenticate himself with his credentials. Once he is authenticated, he will be authorized to see resources/pages of the website. Mostly these two concepts go together and ASP.NET provides us with some server controls that provide a lot of boilerplate functionality out of the box. If we use ASP.NET's authentication and authorization mechanism, then we can focus on what should be authorized and who should be authenticated rather than worrying about how to do that.

Using the Code

ASP.NET provides a lot of control that facilitate the authentication mechanism. Some of the controls that ASP.NET provides for authentication are:

  • Login: this lets the user login using his credentials
  • PasswordRecovery: This control lets the user recover his password.
  • CreateUserWizard: This control lets the user to create an account on the website.
  • ChangePasword: This control will allow users to change their passwords.
  • LoginStatus: This will show whether the user is logged in or not.
  • LoginName: This will display the logged in user's name.

For the authorization part, Roles is the mechanism that ASP.NET uses to authorize users. Each user belongs to one or many roles and the web pages of our site are configured against roles. So if a user belongs to a role that is allowed to view a certain page, he will be able to.

Let us now write a small application to see these controls and concepts in action. We will develop a small website that has three types of users - free users, regular users, and premium users. Each type of user will be able to see their respective list of downloads and the download list of the inferior role, i.e., premium could see regular list and free list, regular could see free list, tec. So let us first create the hierarchy of web pages to achieve this.

Roles and Membership Image

So we have created separate folders for each role and the top level will contain the files for free users. Now we will configure these folders' access. We want two Roles in our application: Regular and Premium, rest of the users will be considered free users.

Let us create the Roles using WSAT (Web Site Administration Tool).

Roles and Membership Image

Once we have the Roles created, we can create the access rules.

Roles and Membership Image

This can be done via WSAT or could be done directly from web.config. Following is the web.config configured for "Premium Users".

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.web>
        <authorization>
            <allow roles="Premium" />
            <deny users="*" />
        </authorization>
    </system.web>
</configuration>
<pre lang="xml">

Once we have done that, we have ensured that the respective folders can only be accessed if the user belongs to a Role. So now obviously the next step would be to create users and assign them Roles.

Before creating users, let's understand that we can use two types of authentication:

  1. Windows authentication: In this type, the users are authenticated on their Windows username and password. This method is least recommended in an internet scenario. In an internet scenario, we should always use "Forms based authentication".
  2. Forms based authentication: In this type of authentication, the user will explicitly have to provide his credentials and these credentials, once verified by the server, will let the user to log in.

So we will be using forms based authentication. We can create users from WSAT and assign them roles.

Roles and Membership Image

Apart from that, we will also create users from the application front-end using ASP.NET server controls. We will have a CreateUserWizard control for that.

Note: We can use the Membership class to perform user management tasks from within the code, such as creating, deleting, or modifying user accounts.

Roles and Membership Image

To assign roles, we will have to do this:

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
{
    if (RadioButtonList1.SelectedValue == "0")
    {
        string username = CreateUserWizard1.UserName;
        Roles.AddUserToRole(username, "Regular");
    }
    else if (RadioButtonList1.SelectedValue == "1")
    {
        string username = CreateUserWizard1.UserName;
        Roles.AddUserToRole(username, "Premium");
    }
}

We will use a Login control to let the user log in.

Roles and Membership Image

We have also added controls like LoginStatus and LoginName in the navigation region to display the login status and logged in user's name.

Roles and Membership Image

Now let us see what pages are there in our application and which user can access which page (apart from the home page).

Roles and Membership Image

This can be accessed by any user who is not logged in and all Regular and Premium users.

Roles and Membership Image

This page can only be accessed by Regular and Premium users.

Roles and Membership Image

This page can only be accessed by Premium users.

Now we have a basic web application working with Roles configured. This application uses all the ASP.NET provided features for authentication and authorization.

Points of Interest

This article talked about the authentication and authorization mechanism provided by ASP.NET. This article is written from a beginner's point of view. This should not be treated as a comprehensive tutorial on Roles and Membership in ASP.NET but as a starting point for learning ASP.NET Roles and Membership.

History

  • 05 March 2012: First version.

License

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

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
India India
I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.
  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4
 
If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionNice tutorial PinmemberMember 1062121724-Feb-14 4:08 
GeneralMy vote of 4 PinprofessionalAmey K Bhatkar25-Jan-14 22:53 
GeneralMy vote of 5 PinprofessionalRenju Vinod27-Aug-13 21:56 
GeneralMy vote of 3 PinmemberAlireza_136227-Aug-13 18:52 
AnswerArticle of the Day on Microsoft's site PinmvpRahul Rajat Singh18-Apr-13 19:14 
GeneralMy vote of 3 Pinmemberjamajda1-Nov-12 4:04 
GeneralMy vote of 4 Pinmemberraisingstar31-Oct-12 10:06 
QuestionRolesNMebership from newbee PinmemberMember 834559924-Aug-12 11:42 
GeneralMy vote of 3 Pinmembersaeedm1217-Aug-12 22:24 
GeneralMy vote of 5 Pinmembersravani.v23-Apr-12 18:59 
GeneralMy vote of 4 PinmemberPhilip Liebscher22-Mar-12 11:45 
GeneralMy vote of 5 Pinmemberpashad20-Mar-12 19:27 
BugUsing MS SQL Database!!!! Pinmemberasdrog20-Mar-12 8:17 
GeneralMy vote of 1 PinmemberBabakArj17-Mar-12 19:16 
NewsRe: My vote of 1 PinmemberPhilip Liebscher22-Mar-12 11:43 
GeneralRe: My vote of 1 PinmemberLannyFly12-Jun-12 20:18 
GeneralMy vote of 4 PingroupPaul @ The Computer Station14-Mar-12 0:40 
GeneralMy vote of 4 PinmemberOshtri Deka8-Mar-12 0:35 
GeneralMy vote of 4 PinmemberDean Oliver7-Mar-12 9:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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.1411023.1 | Last Updated 7 Mar 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid