Secure Your Site

July 25, 2005 12:07 AM
DevConnections
Rating: (0)

ControlFreak

LANGUAGES:VB.NET | C#

ASP.NETVERSIONS: 2.0 (Beta 2)

 

Secure Your Site

Using the new Login Controls in ASP.NET 2.0

 

 

The new Login controls and Membership API in ASP.NET 2.0provide a powerful and automated way to securely store and manage usercredentials. Together, they eliminate nearly all the boilerplate usermanagement code that you?ve likely written many times before. This new systemgoes a long way toward Microsoft?s .NET 2.0 goal of a 70% reduction in theamount of code needed to write an application.

 

To explore these robust new capabilities, create a new Website using Visual Studio 2005. Under the WebSite dropdown menu select ASP.NETConfiguration. A page similar to that shown in Figure 1 will appear. Using thisconfiguration tool, you may never need to manually edit a web.config file everagain! It acts as a front end for editing the web.config file and managingother standard settings, such as the focus of this article: security.

 


Figure 1: You may never need to openanother web.config file ever again. Built-in administration screens make iteasy to configure Web site settings and manage users.

 

The screen shown in Figure 1 says that an Access databasewill be used to store the security settings by default, but this is untrue inBeta 2. Instead, the settings are now stored in a SQL Express database bydefault. This database is named ASPNETDB.MDF. You can interact with thisdatabase like any other database, from the Data Connections node of the ServerExplorer window of Visual Studio. Alternate membership providers can bespecified on the Provider tab. Custom providers can optionally be developed incase you?d like to wrap a legacy authentication system or roll your own.

 

By default, new Web sites use Windows Authentication,which is great for an intranet application. This fictional example will beaccessed from the Internet, so Forms Authentication will be used instead (seeFigure 2).

 


Figure 2: Windows Authentication isenabled for Web sites by default, but Forms Authentication is more appropriatefor Web sites that will be accessed from the Internet.

 

Figure 3 shows a site for which three roles have beenestablished. The majority of users would belong to the User group. The elevatedPremium group might be for paying subscribers, providing them with enhancedfunctionality. The Admin group will be for administrators only. Of course, youcan establish whatever roles are most appropriate for your Web site.

 


Figure 3: Three roles have beencreated in this example: User, Premium, and Admin.

 

After roles have been created, you?ll probably want to addone or more users. This can also be done through the same built-in Web siteconfiguration tool, as shown in Figure 4. A strong password must be specified,so passwords such as ?abc? or ?password? are rejected. Notice that the three rolesconfigured here each have a checkbox, indicating that a user can be a member ofone or more roles. It would be nice if there were a way to configure these tobe option buttons, so that only one group could be specified. It would also benice if there were a way to establish hierarchies, such as specifying that administratorsare automatically members of the User group, but custom validation code stillhas to be written to enforce such matters.

 


Figure 4: New users can be addedthrough this built-in administration screen, so you aren?t forced to re-createsuch boilerplate code.

 

Rules can be established for the folders within a Webapplication to allow or deny access to users and/or roles. Figure 5 shows anAdmin folder that grants access to members of the Admin role, but denies accessto all others.

 


Figure 5: Rules can be establishedfor the folders within a Web application to allow or deny access to users orroles.

 

Now that a basic security framework has been establishedfor the Web site, let?s put together some pages that take advantage of it.

 

Secure Your Site with Login Controls

There?s a new set of controls in the Visual Studio 2005toolbox (under the Login tab). These seven controls automatically interact withthe membership settings configured earlier in this article, so they work fromthe moment you drag them onto the page (see Figure 6). In most cases, little orno code will need to be written to achieve a fully authenticated software system.All of these controls have a SkinID property and an EnableTheming property thatallows a custom look to be applied consistently across controls and pages.

 

New Login Controls

Description

Login

Provides a username and password textbox, associated labels, a working ?remember me? checkbox, validation functionality, and a plethora of customization options.

LoginStatus

Automatically determines whether it should display a Login hyperlink or a Logout hyperlink based on the user?s current authentication status.

LoginView

Displays varying configurable sets of controls based on the user?s current authentication status, optionally considering any roles to which the user may belong.

ChangePassword

Provides a standard Password, New Password, and Verify Password screen that works with no custom code required.

PasswordRecovery

Provides a way for users to retrieve forgotten passwords.

LoginName

Displays the user?s login name when they?re authenticated; otherwise, it?s invisible.

CreateUserWizard

Provides one or more wizard steps to automatically collect user registration data.

Figure 6: These sevennew Login controls in ASP.NET 2.0 dramatically simplify user management andauthentication.

 

Create a new Web page named ?Login.aspx?. Drag a Logincontrol onto this page. This control, shown in Figure 7, provides a User Nameand Password textbox, associated labels, a working ?remember me? checkbox,validation functionality, and a plethora of customization options. You?veprobably constructed similar login screens many times before, and doing so willbe simpler than ever now that the Login control is around to manage suchmatters.

 


Figure 7: The Login control providesall the functionality needed to allow users to log into a Web application, andit?s highly adaptable in case you need to customize it.

 

The smart tag shown in Figure 7 allows easy configuration,such as automatic formatting and the option to convert the control to atemplate. Templates are much more intuitive than they used to be, now that they?revisually editable in the designer.

 

All of the text displayed by the Login control can becustomized via properties, and additional instruction text can be specified, ifnecessary. You can set the VisibleWhenLoggedIn property to False for situationswhere you?d like to have the Login control on all your pages, but only whenrelevant. You can have the control include hyperlinks to other pages, such as aforgotten password page, a help page, or an account creation page. In all, theLogin control provides more than 50 properties that allow various forms ofcustomization. Needless to say, this is a highly flexible control.

 

The LoginStatus control acts as a simple hyperlink at run time.If the user is not logged in, it provides a hyperlink to the login page. If theuser is logged in, it provides ahyperlink that automatically logs them out. You can configure the hyperlinktext, the action the control will take upon logout, and all the URLs involved. TheLogoutAction property accepts one of three values: Refresh, Redirect, orRedirectToLoginPage.

 

The LoginView control displays configurable sets ofcontrols depending on the user?s current login status. For example, it candisplay one set of controls for logged-in users, and a different set ofcontrols for anonymous users. Additionally, it can display different sets ofcontrols for any roles that may have been configured. For example, it candisplay one set of controls for administrators, and another set of controls forstandard users. The smart tag for the control allows you to configure thedifferent roles that the control will handle.

 

The LoginName control simply displays the name of thelogged-in user. This control is invisible when the current user is anonymous. TheFormatString property allows the output to be customized; for example, applythe string ?Welcome, {0}!? to welcome the user by name.

 

Any decent authentication system must also provide a wayto deal with forgotten passwords. The PasswordRecovery control (illustrated inFigure 8) provides rich functionality that permits a user to retrieve aforgotten password. By default, the control will e-mail a forgotten password tothe user?s registered e-mail address after they?ve successfully answered thesecret question that was established upon registration. For this to work, youmust specify a <MailDefinition> child element within the controldefinition:

 

<MailDefinition From="Steve@Orr.net"/>

 

Additionally, the application?s SMTP settings must beconfigured. This is done most easily through the Web site administration tooldescribed earlier.

 


Figure 8: The PasswordRecoverycontrol provides a way for users to retrieve forgotten passwords.

 

Good security measures include changing passwordsregularly. The ChangePassword control (shown in Figure 9) provides all thefunctionality you?re likely to need in this regard. It provides a screensimilar to many you?ve seen before, with a textbox to enter the currentpassword, a textbox to enter the new password, and a third textbox to confirmthe new password. Validation is built in, and a NewPasswordRegularExpressionproperty allows the developer to declaratively require that all new passwordsmatch any pattern imaginable. By default this control will only accept strongpasswords.

 


Figure 9: The ChangePassword controlprovides standard Password, New Password, and Confirm New Password options thatwork with no custom code required.

 

The ChangePassword control is completely configurable,with every bit of text exposed publicly through properties and methods. In casethat?s not enough customization, the entire control can be converted to atemplate via the context menu in the Visual Studio 2005 designer.

 

The CreateUserWizard control is the most functionally-richLogin control of them all. It walks users through the steps involved in establishinga new user account. This highly extensible control can be configured to collectunlimited amounts of data about new users. It can send confirmation e-mails anddefine user roles. Because it inherits from the new Wizard control, it providesthe same level of extensibility. As many steps can be added to the wizard asare needed, and each step can be individually configured via properties orconverted into templates for unlimited levels of customization. Therefore, thiscontrol can meet the requirements whether a quick and dirty solution is neededor whether extensive amounts of detailed user information need to be collected.

 

The boolean LoginCreatedUser property specifies whether anew user should be automatically logged in after they?ve registered. TheDisableCreatedUser property specifies that new user registrations should notbecome active until they?ve been approved.

 

The Infrastructure Below

Clearly the whole set of Login controls are quitepowerful, but what if you prefer not to use them? The whole membershipinfrastructure underlying the Login controls is public, and loosely coupled tothe controls. This means that you don?t need to use the Login controls, becauseyou can directly call the same underlying methods that these controls use.

 

For example, say you?ve got your own user interface anddecided to not use the Login control. You can still easily use the underlyingmembership system to authenticate a user with one line of code:

 

If System.Web.Security.Membership.ValidateUser(UN, PW) Then _

 

The System.Web.Security namespace contains a variety ofuseful and extensible functions. It contains only static methods (known asshared methods in VB) so no object instantiations are needed.

 

Perhaps you?d love to use the Login controls, but haveexisting authentication code that works just great and you?d prefer to keepusing it. No problem; the controls can be hooked up to a custom authenticationsystem with little effort.

 

Whether used together or separately, clearly the new Logincontrols and Membership API are compelling reasons to upgrade to ASP.NET 2.0. Evenif you have an existing authentication you?d like to continue to utilize, bywrapping it inside a custom membership provider you can provide a standardizedinterface to your system, thereby increasing reusability and simplifyingmaintenance.

 

Steve C. Orr is anMCSD and a Microsoft MVP in ASP.NET. He?s been developing software solutionsfor leading companies in the Seattlearea for more than a decade. When he?s not busy designing software systems orwriting about them, he can often be found loitering at local user groups andhabitually lurking in the ASP.NET newsgroup. Find out more about him at http://SteveOrr.netor e-mail him at mailto:Steve@Orr.net.