Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..
SYS-CON.TV
Today's Top SOA Links


Quick and Easy Custom Form-Based Authentication
The new membership, role management, and security features of ASP.NET 'Whidbey'

Building security into intranet Web applications was always easy: just turn on Windows authentication in IIS. But considering the size of the user base for Internet Web applications, custom form-based authentication is the only scalable solution.

If you have built Internet Web applications with ASP 3.0, you know the amount of effort that went into adding form-based authentication. You pretty much had to do everything - build the login form; check for the username and password validity, and if they were valid, write the authentication cookie to the cookies collection of the Response object. Then you had to check for the authentication cookie at the beginning of every page and, if it wasn't present, you had to redirect the user to the login page. And if you wanted to use role-based authorization in the application, you had to write even more code!

The advent of ASP.NET 1.0 brought much-needed relief to ASP developers. By modifying an XML configuration file (Web.config), most of the drudgery of adding form-based authentication was eliminated. But you still had to create the login form, create and maintain a user credential store, and check for user-ID and password validity. And you had to write some additional custom code if you wanted role-based authentication.

ASP.NET 2.0, codenamed "ASP.NET Whidbey," adds a bunch of new features that make building forms-based authentication into applications even faster and simpler.

Membership
First, ASP.NET Whidbey adds the Membership API, which is a user-credentials management interface. The user credentials are stored in a user credentials store. The membership API speaks to the credential store via a provider. ASP.NET Whidbey comes prepackaged with two providers - one for Access and the other for SQL Server. You can write your own custom provider to speak to a user credential store of your choice (for instance, an XML database). The Access provider is the default provider, as shown in Machine.config (see Listing 1).

The heart of the Membership API is the Membership (System.Web.Security.Membership) class. The Membership class is a sealed class that has mostly static properties and methods. Following are some of the commonly used methods of the Membership class:

  1. CreateUser: Used to create a new user.
  2. GetUser: Gets the details of a particular user. Returns an instance of the MembershipUser (Sys-tem.Web.Security.MembershipUser) type.
  3. UpdateUser: Updates user details in the user credentials store. This method accepts an instance of the MembershipUser type.
  4. ValidateUser: Takes a user's credentials (username and password) and returns true if the credentials are valid, and false if they are not.
The functions provided by the Membership API are also available through a Web administration tool, which can be launched using Visual Studio .NET Whidbey's Web Site > ASP.NET Configuration menu option.

The MembershipUser class is another important class. An instance of this class represents a valid user in the application. This class has properties that provide access to user details like the username, e-mail address, and password question. It also has methods that allow you to, among other things, reset the user password, change the user password, and change the password question and answer.

Role Management
Apart from user authentication, most application logic requires some kind of role-based authorization. The Role manager also uses some kind of provider to store the information related to roles and their mappings to users.

The Access provider is the default provider, as seen in Machine.config (see Listing 2). You can change the provider to SQL Server or a custom store by making appropriate changes to Web.config.

The Roles (System.Web.Security.Roles) class can be used to access this information. Some of the important methods of the Roles class are as follows:

  1. CreateRole: Used to create a new role.
  2. GetAllRoles: Used to get all existing roles. It returns an array of strings.
  3. AddUserToRole: Adds a user to a role.
  4. RemoveUserFromRole: Removes a user from a role.
  5. IsUserInRole: Checks if a user belongs to a role.
  6. GetRolesForUser: Gets all roles for a particular user. It returns an array of strings.
Security Server Controls
ASP.NET Whidbey introduces five new server controls specifically designed to reduce the amount of code that developers have to write to add forms-based authentication to their Web applications. Let's drill down into each of these controls, one at a time.

The Login Control
The Login control provides a ready-made login UI that can be embedded in a form, as shown in the following code snippet:

<%@ page language="C#" %>

<script runat="server">

</script>

<html>
<head runat="server">
    <title>Login Page</title>
</head>
<body>
    <form runat="server">
        <asp:login id="login" runat="Server" />
    </form>
</body>
</html>

The output produced by this code is shown in Figure 1.

This is the most basic look provided by the Login control. To achieve this same effect in ASP.NET 1.1 would require about 15 lines of code. The Login control also provides auto-formatting ability through smart tags, as shown in Figure 2.

The Login control fires the authenticate event when the "Log In" button is clicked. This event can be connected to an event handler, as shown in the following code snippet:

<asp:login id="login" runat="server" onauthenticate="AuthenticateUser" />

The event handler validates the username and password provided by the user using the Membership class's ValidateUser method, as shown below. If the credentials provided are valid, the user is redirected away from the login page, as shown in the following code snippet:

void login_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
    if (Membership.ValidateUser (login.UserName, login.Password))    
        FormsAuthentication.RedirectFromLoginPage (login.UserName, false);    
    else    
       login.FailureText = "Login failed. Please try again.";
}

The LoginName Control
The LoginName control displays the name of the logged-in user (User.Identity.Name). It is used as shown below:

<asp:loginname id="loginName" runat="server" />

You could also display a customized greeting by setting the formatstring property of the LoginName control:

<asp:loginname id="loginName" runat="server" formatstring="Welcome, {0}."/>

The LoginStatus Control
If the user is logged in, the LoginStatus control displays a "Logout" link; if the user is logged out, the LoginStatus displays a "Login" link. The link can also be made to show login and logout images. It's used as shown in the following code snippet:

<asp:loginstatus id="loginStatus" runat="server" />

The LoginView Control
The LoginView control is a templated control that has two templates - a template for an anonymous user and a template for a logged-in user. It can also be used to display content based on a user's assigned roles.

Usually, the LoginView control will be used with the LoginName control in its "loggedintemplate", as shown below:

<asp:loginview id="loginView" runat="server">
<anonymoustemplate >
      	Welcome, Guest!
</anonymoustemplate>
<loggedintemplate>
      	<asp:LoginName id="loginName" runat="server" formatstring="Welcome, {0}." />
</loggedintemplate>
<asp:rolegroup roles="Price">
             Content for a prince!
      </asp:rolegroup>
      <asp:rolegroup roles="Pauper">
      	Content for a pauper!
</asp:rolegroup>
</asp:loginview>

The PasswordRecovery Control
People tend to forget passwords. Therefore, most Web sites provide a password-recovery feature. In the case of a forgotten password, this functionality mails the user:

  1. A random password, or
  2. The existing password, only after the user has provided the correct answer to the password question (which was set up during signup)
Adding such functionality in ASP 1.0/1.1 would involve writing approximately 50 lines of code. In ASP.NET Whidbey the PasswordRecovery control takes care of it in 3 lines of presentation-layer code:

<asp:passwordrecovery id="passwordrecovery" runat="server">
<maildefinition from="support@fooinc.com" />
</asp:passwordrecovery>

Figure 3 shows how this control appears in the browser.

To allow the user to retrieve the current password, the following changes must be made in the <membership> section of Web.config: the enablePasswordRetrieval attribute has to be set to true, and the passwordFormat attribute has to be set to "Clear" or "Encrypted" (as opposed to "Hashed", which is a one-way encryption that makes it impossible to retrieve the password). To allow the recovery of the current password by providing the answer to the password question, the requiresQuestionAndAnswer property must also be set to true.

By setting only the enableReset-Password attribute of the <membership> section to true, the user has the ability to request a new random password.

Conclusion
This was a brief walkthrough of the new security features introduced in ASP.NET Whidbey. After reading through this article, it should be clear to all that no one knows the pulse of Web developers better than the ASP.NET team.

About Mujtaba Syed
Mujtaba Syed works as a software architect with Marlabs Inc. He is an MCSD
(early achiever) and loves to speak about and write on Microsoft .NET. Mujtaba has been programming the Microsoft .NET Framework since its beta 1 release. His current interests are focused on Longhorn.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Easy to understand article.


Your Feedback
Venu wrote: Easy to understand article.
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021

SYS-CON Featured Whitepapers
ADS BY GOOGLE