ASP. NET 2.0 login Control

Source: Internet
Author: User
Tags microsoft access database
Author: Keith Brown
Related Technologies: security, ASP. NET 2.0
Difficulty:★★☆☆☆

[Guide]ASP. NET 2.0 gives developers great confidence in the newly introduced server segment security controls, role definitions, password recovery, and member-and role-based programming, Asp. NET 2.0 makes your system more secure and reliable.

The new security feature is a major improvement in ASP. NET 2.0. These functions include the membership service for Managing User Account databases, the hash password, and the role manager for Managing User role member identities, and five new server-side controls that are easier to implement form authentication. ASP. NET 2.0 also provides a provider model that gives you full control over membership and role services and the implementation of cookieless form authentication. You can also easily perform simple, Web-based local and remote management of user accounts and roles, and gain enhanced control over other non-security-related settings.

Repush form Authentication

Form authentication is one of the most widely used functions in ASP. NET 1.0, because it encapsulates the best practices that many specific implementations lack. For example, do you know how many form authentication implementations can protect the integrity of cookies used to store client creden? Form authentication not only writes the user name to the cookie, but also adds a message authentication code (a hash value based on the cookie and a secret value only known by the Web server ). This prevents malicious clients from viewing data of other users by increasing their permissions or modifying the name in their cookies.

If you note. various news groups and list servers launched by web developers. You will understand that people are implementing the same thing over and over again: roles cached in user databases and cookies, controls for capturing user names and passwords, and tools for managing users and roles. The ASP. Net team has provided built-in solutions for almost all of these problems. When studying ASP. NET 2.0 Alpha, I found that the amount of code used to build a web site that uses form authentication in a manageable manner decreases dramatically.

Getting started

If you have ASP. NET 2.0 (which can be used in msdn), you will find out how easy it is to start using these new features when rehearsing some experiments that can be executed! Normal subscribers can download data.

To start downloading, you need a virtual directory pointing to an empty directory. You must ensure that the ASP. NET auxiliary process has the permission to read, execute, and write to this directory. If you are running Windows 2000 or Windows XP, You need to grant these permissions to the local ASP. NET account. For Windows Server 2003, You need to grant these permissions to the network service account.

I will use form authentication, so I need to enable it through the Web. config file. If I show you how to use ASP. NET 1.1, open a text editor and start typing XML manually. However, in ASP. NET 2.0, one of my favorite features is the interactive configuration file editor, which is directly built on the IIS console. You can go to the "ASP.. Net tab. Click "Edit configuration" to open the editor.


Figure 1 configuration Editor

Figure 1 shows the new editor. You will see that I have selected form authentication instead of the default option: Windows authentication. Perform the same operation in your own virtual directory. When you use the configuration tool, set the default language of the Web application to C #, because it will save some of the subsequent input for you. "Page language default" is the first drop-down option on the Application tab. After these changes are applied, you will find the Web. config file in the directory with all the settings.

You need to register some users with the membership service to start, so the first page of writing is the page that allows users to be added. This test version provides a server control. You can use the following three lines of code to implement this page:

<Form runat = 'server'>
<Asp: createuser runat = 'server'/>
</Form>

<Form runat = 'server'>
<Table>
<Tr> <TD> name: </TD> <asp: textbox id = 'name' runat = 'server'/> </TD> </tr>
<Tr> <TD> email address: </TD> <asp: textbox
Id = 'email 'runat = 'server'/>
</TD> </tr>
<Tr> <TD> password: </TD> <asp: textbox textmode = 'Password'
Id = 'pwd1 'runat = 'server'/>
</TD> </tr>
<Tr> <TD> retype password: </TD> <asp: textbox textmode = 'Password'
Id = 'pwd2 'runat = 'server'/>
</TD> </tr>
</Table>
<Asp: button text = 'submit 'onclick = 'onsubmit' runat = 'server'/>
<P> <asp: Label id = 'msg 'runat = 'server'/> </P>
</Form>

<SCRIPT runat = 'server'>
Void onsubmit (Object sender, eventargs ARGs)
{
If (pwd1.text. Equals (pwd2.text ))
{
Membershipcreatestatus status;
Membershipuser newuser = membership. createuser (name. Text,
Pwd1.text, email. Text, out status );
MSG. Text = status. tostring ();
}
Else
MSG. Text = "passwords don't match, try again .";
}
</SCRIPT>

Figure 2 adduser. aspx

However, since the version I used is Alpha, I must use the membership class to manually write code for this special form. Now, you only need to use the ASPX page shown in Figure 2. I will discuss the membership class later in this article. Figure 3 shows what you see when you direct your browser to this page. Continue the test. Now add some users and passwords. After success, your work should be easier!


Figure 3 Member page

After adding a user, check the virtual directory carefully. You should see a new subdirectory named "data", which contains a Microsoft Access database. This is where membership and role services store their data by default, but I will show you how to override the default storage mechanism to use SQL Server or your own custom data repository later. Now, you can use security controls in ASP. NET 2.0.

Server-side security controls

Figure 4 lists the five new security controls in ASP. NET 2.0. It is a good idea to start exploring the loginstatus control. First, create a new ASPX page containing the control. For simplicity, call the new page default. aspx:

<Form runat = 'server'>
<Asp: loginstatus runat = 'server'/>
</Form>

Widget Description
Loginstatus Provides a logon or logout button, depending on the user's current status
Login Provide a form for collecting and verifying logon creden dependent on the user database
Loginname Display a user name that has been logged on
Loginview Display specific content, depending on whether the user logs on, and whether the user is a role member is optional
Passwordrecovery Provides a list of forgotten passwords.

Figure 4 new security control of ASP. NET 2.0

Point the browser to this page and you should see a login link. If you view the source code of the result page in the browser, you will see that this hyperlink points to a page named login. aspx, but you have not compiled it yet. This is a Web page implemented with three lines of code. Therefore, we will continue the experiment and create it now:

<Form runat = 'server'>
<Asp: Login runat = 'server'/>
</Form>

If you have manually implemented form authentication, you will appreciate the three lines of code. In the past, the equivalent Implementation of database search requires two times of code.

Now go back to your browser and click the login link, which will take you to the logon page 5, as shown in. If you try to log on with an invalid user name or password, an appropriate default error message will pop up. This message does not give attackers too much information. An inexperienced developer will never accidentally send a message back to the user, telling him that he has obtained the correct user name. Please try to guess another password!


Figure 5 logon page

Continue and enter a valid user name and password. This is the user name and password you previously entered on the adduser. ASPX page, and you should be redirected back to the default. aspx page. Because you do not provide any custom operations for the logon control, by default, it only allows you to log on through form authentication, this means that your browser now has an encrypted cookie that stores the user name.

Since you have redirected back to the default. aspx page, do you see any difference? The logon Status control should now display logout instead of login. Because the form authentication cookie is sent together with the request, formsauthenticationmodule creates an authenticated user subject and associates it with the request context. The logon Status control will notice this situation and change to allow you to log out. Log out and log on again to view the job.

Now, let's add some code to the default. aspx page:

<H3> User name: <% = user. Identity. name %> <H3> User Type: <% = user. GetType () %>

Refresh the page and you will see the username you used to log on. Note that the basic object of a user is of the genericprincipal type. This is the form that formsauthenticationmodule represents the user. Once you start role manager, you will notice this type change, because when enabled, the new rolemanagermodule replaces the User Generated by formsauthentication using its own type.

Now, let's add a loginview control to the default. aspx page to display the content that can be changed based on the user's login. The simplest way to use this control is to provide two content blocks: one for anonymous requests (before the user logs on) and the other for identity authentication requests (after the user logs on ):

<Asp: loginview runat = 'server'>
<Anonymoustemplate>
<H4> if you see this, you 've not yet logged in! </H4>
</Anonymoustemplate>
<Loggedintemplate>
<H4> welcome to my website, <asp: loginname runat = 'server'/>! </H4>
</Loggedintemplate>
</ASP: loginview>

When you log on or log out, you should see that the text in the loginview control has changed, as we expected. This is a simple idea, but it does make your code clearer.

Define roles

I have created a simple page that allows you to use role manager to add users to roles. However, before you can use it, you also need to enable role manager for the application. Go back to the configuration tool and find the authentication tab. Select the check box marked with "role management enabled" and apply this change.

<Form runat = 'server'>
<Table>
<Tr> <TD> role: </TD> <asp: textbox id = 'role' runat = 'server'/> </TD> </tr>
<Tr> <TD> User: </TD> <asp: textbox id = 'user' runat = 'server'/> </TD> </tr>
</Table>
<Asp: button text = 'add user to role! 'Onclick = 'onsubmit 'runat = 'server'/>
<P> <asp: Label id = 'msg 'runat = 'server' viewstateenabled = 'false'/> </P>
</Form>

<SCRIPT runat = 'server'>
Void onsubmit (Object sender, eventargs ARGs)
{
If (! Roles. roleexists (role. Text ))
{
Roles. createrole (role. Text );
MSG. Text = "created a new role .";
}
Roles. addusertorole (user. Text, role. Text );
}
</SCRIPT>

Figure 6 addrole. aspx

The code of the addrole. ASPX page is displayed in figure 6, while Figure 7 shows the appearance of the form. Place the page in the virtual directory and direct the browser to it, so that you can add some roles. Specify a user name (the user name you added in the adduser. aspx form) and a role name, and then press the button to add the user to the role. The code first adds a role (if it does not exist) and then adds the user to the role. In the background, role manager tracks these role mappings in the same Microsoft Access database used by the membership service, but this is actually a coincidence. Role manager can store its data in SQL Server or any other storage without having to use the same mechanism as the membership service. Therefore, membership and role manager provide different program models.


Figure 7 Add a role

If you have been in ASP. net, you will certainly appreciate the built-in role manager, because you no longer need to become an ASP.. Net HTTP pipeline supervisor can achieve role-based security. Once you have added some roles, you can return to default. aspx and use the loginview control to do something interesting. Add another part after the <loggedintemplate/> element:

<Rolegroups>
<Asp: rolegroup roles = 'forummoderators '>
<Contenttemplate>
<H4> controls for Forum moderators go here. </H4>
</Contenttemplate>
</ASP: rolegroup>
<Asp: rolegroup roles = 'ds DS '>
<Contenttemplate>
<H4> Welcome, friend! </H4>
</Contenttemplate>
</ASP: rolegroup>
</Rolegroups>

You may not select the same role as me. Therefore, you need to replace my role name with your own role name and adjust the content to make it suitable for the role. After logon, you can use different user accounts in different roles to check your new page and observe how the page content changes when the role changes. Note that if both role groups match the user role, the first matched role group is always displayed (from top to bottom ).

Although this is not new, remember that you can always test the role programmatically through user. isinrole. Note that you can use the section in Web. config to allow or deny access to each page, as shown below:

<Authorization>
<Deny users = '? '/>
<Allow roles = 'forummoderators '/>
<Deny users = '*'/>
</Authorization>

The first item tells ASP. NET to prohibit any request without authentication (force authentication ). The second and third items ensure that only forummoderators can access the contents in the directory tree where the Web. config file resides. Remember, the authorization part can be used for the Web. config file in the subdirectory or for elements to control access to individual files.

Passwordrecovery password restoration control

This control allows you to easily restore the password prompt and email the password to the user. The Code is as follows:

<Asp: passwordrecovery id = "prforgotpass" runat = "server"> </ASP: passwordrecovery>

The implementation is shown in:

After you enter the user name, you need to enter the password to restore the answer, for example:

In the control, set and email the restored password to the user.

<Asp: passwordrecovery id = "prforgotpass" runat = "server">
<Maildefinition
Bodyfilename = "forgotpassword.txt"
From = "helpdesk@dorknozzle.com"
Subject = "Word has it, you forgot your password? "/>
</ASP: passwordrecovery>

  Changepassword

You can easily change the password by changing the password control, including a maildefinition attribute. If the value is assigned to the maildefinition attribute, the changepassword control automatically sends an email to the user when the password is successfully changed.

  Directly use the membership API

Sometimes, a higher level of control (higher than the control level provided by the web site management tool or login Control) needs to be performed on the member identity. In these cases, you can directly use the membership API.

The membership API is made public through the membership class. The membership class allows you to do the following: Create a new user, change the password, and search for users matching a specific condition. Behind the scenes, the login control uses these methods to interact with the configured membership provider.

Some important methods of the membership class are listed below:

Createuser-allows you to create new users.

Deleteuser-allows you to delete existing users.

Findusersbyemail-enables you to retrieve a set of users that match a specific email address.

Findusersbyname-enables you to retrieve user sets that match a specific user name.

Generatepassword-enables you to generate random passwords.

Getallusers-enables you to retrieve all users stored in the membership provider.

Getnumberofusersonline-enables you to return the number of users currently accessing Web applications.

Getuser-enables you to retrieve the member identity information associated with the current user, or enables you to retrieve the member identity information associated with a user who has provided the user name.

Getusernamebyemail-enables you to retrieve the user name of a user with a specific email address.

Updateuser-enables you to update information of a specific user.

Validateuser-enables you to authenticate a user based on the membership identity Provider.

Finally, we use this API to implement slightly more complex functions. In index. aspx, add a label control to display the number of online users. The Code is as follows:

Number of users online:
<Asp: Label id = "lblnumusersonline" runat = "server"/>

In the page-load event, add the following code:

Sub page_load (S as object, e as eventargs) handles mybase. Load
Lblnumusersonline. Text = _
Membership. getnumberofusersonline (). tostring ()
End sub

The number of online users is displayed. In addition, we add a gridview to display the online status of all users, whether certain permissions and related information are allowed.

<Asp: gridview id = "gvusers" runat = "server" autogeneratecolumns = "false">
<Columns>
<Asp: boundfield headertext = "username" datafield = "username"/>
<Asp: boundfield headertext = "is online? "Datafield =" isonline "/>
<Asp: boundfield headertext = "is approved? "Datafield =" isapproved "/>
<Asp: boundfield headertext = "email" datafield = "email"/>
</Columns>
</ASP: gridview>

And bind the gridview:

Gvusers. datasource = membership. getallusers ();
Gvusers. databind ();

The final running result is as follows:

  Summary:

This article introduces the simple usage of the newly added logon control series in Asp.net 2.0 and the simple use of the newly added membership API, for more information, see msdn or the official version.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.