How to use C #. Net to implement form-based authentication in ASP. NET?

Source: Internet
Author: User
Translation: mydotnet

This article Article The following namespace is referenced in the Microsoft. NET Class Library:
System. Data. sqlclient
System. Web. Security
-------------------------------
Task:
Abstract:
1. Requirements
2. Use Visual C #. Net to create an ASP. NET application Program
3. Configure security settings in the web. config file
4. Create a database table sample to store user data
5. Create a logon. ASPX page
6. Write event processing Code To verify user identity
7. Create a default. aspx page
8. Additional prompts
References
-------------------------------
Summary
This article demonstrates how to implement form-based verification by storing user information in the database.
(1) Requirements
The following tools are required for implementation:
1. Microsoft Visual Studio. NET
2. Microsoft Internet Information Services (IIS) version 5.0 or update
3. Microsoft SQL Server
(2) Use C #. Net to create ASP. NET Applications
1. Open Visual Studio. NET
2. Create a new ASP. NET web application and specify the name and path.
(3) Configure security settings in the web. config file
This section demonstrates how to configure ASP. NET applications by adding and modifying <authentication> and <authorization> nodes to implement form-based verification.
1. Open the Web. config file in the solution window.
2. Change the Authentication Mode to forms (note: the default mode is windows)
3. insert the <forms> tag and enter the appropriate attributes. (please refer to the msdn document or Quickstart document listed at the end of the article to view these attributes.) first copy the following code and then paste it in the <authentication> section:

<Authentication mode = "forms">
<Form name = ". aspxformsdemo" loginurl = "Logon. aspx" Protection = "all" Path = "/" timeout = "30"/>
</Authentication>
(Note: If loginurl is not specified, the default value is default. aspx)

4. Add the following nodes to reject anonymous access:
<Authentication>
<Deny users = "? "/>
<Allow users = "*"/>
</Authentication>

(4) Create a database table sample to store user data
This section demonstrates how to create a sample database to store user names, passwords, and user roles. if you want to implement role-based security, it is necessary to add a field for storing user roles in the database.
1. Open notepad.
2. Copy the following script to notepad and save it:

If exists (select * From sysobjects where id =
Object_id (n' [DBO]. [users] ') and objectproperty (ID, n'isusertable') = 1)
Drop table [DBO]. [users]
Go
Create Table [DBO]. [users] (
[Uname] [varchar] (15) not null,
[PWD] [varchar] (25) not null,
[Userrole] [varchar] (25) not null,
) On [primary]
Go
Alter table [DBO]. [users] With nocheck add
Constraint [pk_users] primary key nonclustered
(
[Uname]
) On [primary]
Go

Insert into users values ('user1', 'user1', 'manager ')
Insert into users values ('user2', 'user2', 'admin ')
Insert into users values ('user3', 'user3', 'user ')
Go
3. Open Microsoft SQL Server, open the query analyzer, select the pubs database in the Database List, and paste the above script to run it. In this case, an example User table will be created in the pubs database and will be used in this sample program.
(5) create a logon. ASPX page
1. Create a new web form named logon. aspx in the created Project.
2. Open logon. aspx in the editor and switch to the HTML view.
3. Copy the following code, select "paste as HTML" in the editing menu, and insert it between <form> labels.
<H3>
<Font face = "verdana"> logon page </font>
</H3>
<Table>
<Tr>
<TD> Email: </TD>
<TD> <input id = "txtusername" type = "text" runat = "server"> </TD>
<TD> <asp: requiredfieldvalidator controltovalidate = "txtusername"
Display = "static" errormessage = "*" runat = "server"
Id = "vusername"/> </TD>
</Tr>
<Tr>
<TD> password: </TD>
<TD> <input id = "txtuserpass" type = "password" runat = "server"> </TD>
<TD> <asp: requiredfieldvalidator controltovalidate = "txtuserpass"
Display = "static" errormessage = "*" runat = "server"
Id = "vuserpass"/>
</TD>
</Tr>
<Tr>
<TD> persistent COOKIE: </TD>
<TD> <asp: checkbox id = "chkpersistcookie" runat = "server" autopostback = "false"/> </TD>
<TD> </TD>
</Tr>
</Table>
<Input type = "Submit" value = "Logon" runat = "server" id = "login Login"> <p> </P>
<Asp: Label id = "lblmsg" forecolor = "red" font-name = "verdana" font-size = "10" runat = "server"/>

This page is used to display a login form so that users can provide their usernames and passwords and record them in the application.
4. Switch to the design view and save the page.

(6) Write event processing code to verify user identity
The following code is stored in the Post-code page (logon. aspx. CS)
1. Double-click the logon page to open the logon. aspx. CS file.
2. Import the necessary namespace in the Post-code file:
Using system. Data. sqlclient;
Using system. Web. Security;
3. Create a validateuser function to verify the identity of the user by searching for the user in the database. (Please change the database connection string to point to your database)
Private bool validateuser (string username, string password)
{
Sqlconnection conn;
Sqlcommand cmd;
String lookuppassword = NULL;

// Check for invalid username.
// Username must not be null and must be between 1 and 15 characters.
If (null = username) | (0 = username. Length) | (username. length> 15 ))
{
System. Diagnostics. Trace. writeline ("[validateuser] Input Validation of username failed .");
Return false;
}

// Check for invalid password.
// Password must not be null and must be between 1 and 25 characters.
If (null = PASSWORD) | (0 = password. Length) | (password. length> 25 ))
{
System. Diagnostics. Trace. writeline ("[validateuser] Input Validation of password failed .");
Return false;
}

Try
{
// Consult with your SQL Server administrator for an appropriate connection
// String to use to connect to your local SQL Server.
Conn = new sqlconnection ("Server = localhost; Integrated Security = sspi; database = pubs ");
Conn. open ();

// Create sqlcommand to select PWD field from users table given supplied username.
Cmd = new sqlcommand ("select PWD from users where uname = @ username", Conn );
Cmd. Parameters. Add ("@ username", sqldbtype. varchar, 25 );
Cmd. Parameters ["@ username"]. value = username;

// Execute Command and fetch PWD field into lookuppassword string.
Lookuppassword = (string) cmd. executescalar ();

// Cleanup command and connection objects.
Cmd. Dispose ();
Conn. Dispose ();
}
Catch (exception ex)
{
// Add error handling here for debugging.
// This error message shocould not be sent back to the caller.
System. Diagnostics. Trace. writeline ("[validateuser] exception" + ex. Message );
}

// If no password found, return false.
If (null = lookuppassword)
{
// You cocould write failed login attempts here to event log for additional security.
Return false;
}

// Compare lookuppassword and input password, using a case-sensitive comparison.
Return (0 = string. Compare (lookuppassword, password, false ));

}
(Note: This code first checks whether the entered user name and password meet certain conditions. As shown above, if yes, connect to the database and retrieve the password based on the user name and return the password, finally, judge whether the obtained password is null. If not empty, then judge whether the obtained password is the same as the entered password. The final false parameter is case insensitive)

4. Use one of the following two methods in the cmdlogin_serverlick event to generate a Form Verification cookie and forward the page to the specified page.
The following provides sample code for two methods, which can be selected based on your needs.
A) call the redirectfromloginpage method in the cmdlogin_serverclick event to automatically generate a Form Verification cookie and direct the page to a specified page.
Private void upload login_serverclick (Object sender, system. eventargs E)
{
If (validateuser (txtusername. Value, txtuserpass. Value ))

Formsauthentication. redirectfromloginpage (txtusername. Value, chkpresistcookie. Checked );
Else
Response. Redirect ("Logon. aspx", true );

}

B) generate an encrypted authentication ticket, create a response cookie, and redirect the user. This method gives you more control over how to create a cookie. You can also include custom data together with formsauthenticationticket.
Private void upload login_serverclick (Object sender, system. eventargs E)
{
If (validateuser (txtusername. Value, txtuserpass. Value ))
{
Formsauthenticationticket tkt;
String cookiestr;
Httpcookie CK;
Tkt = new formsauthenticationticket (1, txtusername. value, datetime. now, datetime. now. addminutes (30), chkpersistcookie. checked, "your custom data"); // create a verification ticket
Cookiestr = formsauthentication. Encrypt (tkt); // and encrypt the ticket
Ck = new httpcookie (formsauthentication. formscookiename, cookiestr); // create a cookie
If (chkpersistcookie. Checked) // if the user chooses to save the password
CK. expires = tkt. expiratioin; // set the cookie Validity Period
CK. Path = formsauthentication. formscookiepath; // cookie storage path
Response. Cookies. Add (CK );
String strredirect;
Strredirect = request ["returnurl"];
If (strredirect = NULL)
Strredirect = "default. aspx ";
Response. Redirect (strredirect, true );
}
Else
Reponse. Redirect ("Logon. aspx", true );
}
5. Make sure that the following code is available in the inititalizecomponent method:
This. login Login. serverclick + = new system. eventhandler (this. login login_serverclick );

(7) create a default. aspx page
This section creates a test page to redirect to the page after user verification. If the user is not recorded for the first time, the user will be redirected to the logon page.
1. rename the existing webform1.aspx to default. aspx and open it in the editor.

2. Switch to the HTML view and copy the following code to the <form> tag:
<Input type = "Submit" value = "signout" runat = "server" id = "cmdsignout">
This button is used to cancel the Form Verification session.
3. Switch to the design view and save the page.
4. Import the necessary namespace in the Post-code:
Using system. Web. Security;
5. Double-click the singout button to open the post code (default. aspx. CS) and copy the following code to the cmdsingout_serverclick event processing:
Private void upload signout_serverclick (Object sender, system. eventargs E)
{
Formsauthentication. signout (); // deregister
Response. Redirect ("Logon. aspx", true );
}
6. Check that the inititalizecomponent method contains the following code:
This. inclusignout. serverclick + = new system. eventhandler (this. inclusignout_serverclick );
7. Save the compilation project. Now you can run this application.
(8) Additional prompts
1. If you want to securely store passwords in the database, you can use the hashpasswordforstoringinconfigfile function in the formsauthentication class before storing the data. (Note: A hash password will be generated)
2. SQL connection information can be stored in the configuration file (Web. config) to facilitate modification as needed.
3. Some code can be added to prevent hackers from using the brute force method to log on. For example, you can only have two or three logon opportunities by adding some logic. If the user cannot log on within the specified number of logins, you can set a flag in the database to prevent the user from logging on until the user accesses another page or asks for help. In addition, you can add some appropriate error handling as needed.
4. Because users are identified based on authentication cookies, Secure Sockets Layer (SSL) can be used in applications to protect authentication cookies and other useful information.
5. form-based authentication requires the client's browser to accept or enable cookies.
6. the timeout parameter in the <authentication> Configuration section is used to control the interval between re-occurrence of cookies. You can assign a proper value to it to provide better performance and security.
7. Some proxy servers or caches on the Internet may cache some Web server responses that will be returned to another user with the set-Cookie header. Because form-based authentication uses cookies to authenticate users, passing through the intermediate proxy server or buffering may cause users to be accidentally mistakenly identified as users who are not sending them.


References:
If you want to know how to configure the <credentials> node to store the user name and password for form-based authentication, refer to the following gotdotnet ASP. NET Quickstart example:
Form-based verification: http://www.gotdotnet.com/QuickStart/aspplus/default.aspx? Url =/Quickstart/aspplus/doc/formsauth. aspx
If you want to know how to use an XML file to store the user name and password for form-based authentication, refer to the following example in the SDK documentation:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconcookieauthenticationusinganxmlusersfile. asp
For more information about ASP. NET security, see the Microsoft. NET Framework developer's guide document:
ASP. NET: http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconaspnetwebapplicationsecurity. asp
For more information about the system. Web. Security namespace, see:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpref/html/frlrfsystemwebsecurity. asp
For more information about ASP. NET configuration, see the Microsoft. NET Framework developer's guide document:
ASP. NET Configuration:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpconaspnetconfiguration. asp
ASP. NET configuration node:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpgrfaspnetconfigurationsections. asp
For more information about ASP. NET security, see msdn:
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/dnbda/html/authaspdotnet. asp
For more information about ASP. NET, see the msdn newsgroup:
Http://go.microsoft.com/fwlink? Linkid = 5811 & clcid = 0x409

This article applies:
Microsoft ASP. NET (supported with the. NET Framework 1.1)
Microsoft Visual C #. Net (2003)
Microsoft ASP. NET (supported with the. NET Framework) 1.0
Microsoft Visual C #. Net (2002)
Microsoft SQL Server 2000 (all editions)
Microsoft SQL Server 7.0
Microsoft SQL Server 2000 64-bit (all editions)

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.