How to use C # in asp.net. NET implements forms based validation (ii)

Source: Internet
Author: User
Tags datetime documentation empty error handling implement log microsoft sql server ticket
asp.net

(v) Create logon.aspx pages
1. Create a new Web form, named Logon.aspx, in a project that has already been created.
2. Open Logon.aspx in the editor and switch to HTML view.
3. Copy the following code and insert it between the <form> tags in the Edit menu, "Choose Paste as HTML" option.

12 <font face= "Verdana" >logon page</font>
34<table>
5 <tr>
6 <td>Email:</td>
7 <td><input id= "txtUserName" type= "text" runat= "Server" ></td>
8 <td><asp:requiredfieldvalidator controltovalidate= "txtUserName"
9 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>
25</table>
26<input type= "Submit" value= "Logon" runat= "Server" id= "Cmdlogin" ><p></p>
27<asp:label id= "lblmsg" forecolor= "Red" font-name= "Verdana" font-size= "a" runat= "Server"/>
28 This page is used to display a login form so that users can provide their user name and password and log in to the application.
4. Switch to Design view to save this page.

(vi) Writing event-handling codes to authenticate user identities
The following code is placed in the Back code page (Logon.aspx.cs)
1. Double-click the logon page to open the Logon.aspx.cs file.
2. Import the necessary name space in the post code file:
Using System.Data.SqlClient;
Using System.Web.Security;
3. Create a ValidateUser function that verifies the identity of the user by locating the user in the database. (Please change the database connection string to point to your database)
1private bool ValidateUser (string userName, String PassWord)
2{
3SqlConnection Conn;
4SqlCommand cmd;
5string lookuppassword = null;
6
7//Check for invalid userName.
8//UserName must is null and must be between 1 and characters.
9if (null = userName) | | (0 = username.length) | | (Username.length > 15))
10{
One System.Diagnostics.Trace.WriteLine ("[ValidateUser] Input validation of UserName failed.");
return false;
13}
14
15//Check for invalid PassWord.
16//PassWord must is null and must be between 1 and characters.
17if (null = PassWord) | | (0 = password.length) | | (Password.length > 25))
18{
System.Diagnostics.Trace.WriteLine ("[ValidateUser] Input validation of PassWord failed.");
return false;
21}
22
23try
049
//Consult with your SQL Server administrator for a appropriate connection
num//String to use to connect to your local SQL Server.
conn = new SqlConnection ("server=localhost;integrated security=sspi;database=pubs");
Conn. Open ();
29
//Create SqlCommand to select PWD field from users table given supplied UserName.
To cmd = new SqlCommand ("Select pwd from Users where Uname= @userName", conn);
The cmd. Parameters.Add ("@userName", SqlDbType.VarChar, 25);
to CMD. parameters["@userName"]. Value = UserName;
34
The//Execute command and Fetch pwd field into Lookuppassword string.
Lookuppassword = (string) cmd. ExecuteScalar ();
37
Cleanup command and Connection objects.
to CMD. Dispose ();
Conn. Dispose ();
41}
42catch (Exception ex)
43{
The//ADD error handling here is for debugging.
The should//This error message is sent to the caller.
System.Diagnostics.Trace.WriteLine ("[ValidateUser] Exception" + ex. message);
47}
48
49//If no password found, return false.
50if (Null = = Lookuppassword)
51{
I//You could write failed login attempts this to the event log for additional security.
return false;
54}
55
56//Compare lookuppassword and input PassWord, using a case-sensitive comparison.
57return (0 = = String.Compare (Lookuppassword, PassWord, false));
58
59}
60
(Note: This code means to first determine whether the user name and password entered meet certain conditions, for example, if the match is connected to the database, and according to the user name to remove the password and return the password, and finally to determine whether the removed password is empty, if not empty then judge the password and entered the password is the same, The last false argument is case-insensitive)

4. Use one of the following two methods in the Cmdlogin_serverlick event to generate a cookie for form authentication and to move the page to the specified page.
The following provides sample code for two methods, depending on what you need to choose.
A RedirectFromLoginPage method is invoked in the cmdLogin_ServerClick event to automatically generate the form authentication cookie and to direct the page to a specified page.
private void cmdLogin_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 encryption verification ticket, create a response cookie, and redirect the user. This gives you more control over how to create cookies, and you can also include some custom data along with FormsAuthenticationTicket.
1private void cmdLogin_ServerClick (Object Sender,system.eventargs e)
2{
3 if (ValidateUser (Txtusername.value,txtuserpass.value))
4 {
5 FormsAuthenticationTicket tkt;
6 string cookiestr;
7 HttpCookie ck;
8 Tkt=new FormsAuthenticationTicket (1,txtusername.value,datetime.now,datetime.now.addminutes (30), chkPersistCookie.Checked, "Your custom Data"); Create a validation ticket
9 Cookiestr=formsauthentication.encrypt (TKT);//and encrypted bill
Ck=new HttpCookie (FORMSAUTHENTICATION.FORMSCOOKIENAME,COOKIESTR);//Create Cookie
One if (chkpersistcookie.checked)//If the user chooses to save the password
ck. Expires=tkt. expiratioin;//Set Cookie Expiration
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);
20}
Else
Reponse.redirect ("Logon.aspx", true);
23}
245. Make sure you have the following code in the Inititalizecomponent method:
This.cmdLogin.ServerClick + = new System.EventHandler (This.cmdlogin_serverclick);
(vii) Create a Default.aspx page
This section creates a test page to be redirected to when the user has finished validating the page. If the user browses to this page for the first time without being logged, the user will be redirected to the login page.
1. Rename the existing WebForm1.aspx to Default.aspx and open them in the editor.

2. Switch to HTML view, copy the following code between <form> tags:
<input type= "Submit" value= "SignOut" runat= "Server" id= "Cmdsignout" >
This button is used to unregister the form verification session.
3. Switch to Design view to save the page.
4. Import the necessary name space in the post code:
Using System.Web.Security;
5. Double-click the Singout button to open the back code (Default.aspx.cs), and then copy the following code to the Cmdsingout_serverclick event handler:
private void cmdSignOut_ServerClick (Object Sender,system.eventargs e)
{
FormsAuthentication.SignOut ()/Logoff
Response.Redirect ("Logon.aspx", true);
}
6. Please confirm that the following code is available in the Inititalizecomponent method:
This.cmdSignOut.ServerClick + = new System.EventHandler (This.cmdsignout_serverclick);
7. Save the build project, you can now run the application.
(eight) Additional hints
1. If you want to securely store passwords in the database, you can encrypt them by using the HashPasswordForStoringInConfigFile function in the FormsAuthentication class before storing the data. (Note: A hash password will be generated)
2. You can store SQL connection information in a configuration file (Web.config) to facilitate modification when needed.
3. Some code can be added to prevent hackers from using the exhaustive method to log in. For example, adding some logic allows users to have only two or three logon opportunities. If a user cannot log in for a specified number of logons, you can set a marker in the database to prevent the user from logging in until the user accesses another page or requests your help. In addition, you can add some appropriate error handling as needed.
4. Because the user is identified based on the authentication cookie, Secure Sockets Layer (SSL) can be used in the application to protect the authentication cookie and other useful information.
5. Form-based authentication requires the client's browser to accept or enable cookies.
6. The timeout parameters in the <authentication> configuration section are used to control the time between the cookies being restarted. It can be assigned an appropriate value to provide better performance and security.
7. Some proxy servers or buffers on the Internet may cache some Web server responses that will return to another user, including the Set-cookie header. Because the form based validation uses cookies to authenticate the user, passing an intermediary proxy server or buffering may cause the user to be accidentally mistaken for a user who is not intended to be sent to him.


Reference articles:
If you want to know how to implement a form based validation by configuring <credentials> node for a user name and password, refer to the following gotdotnet asp.net QuickStart examples:
Form-based validation: 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 hold a user name and password to implement a form-based validation, refer to the following example in the SDK documentation:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/ Cpconcookieauthenticationusinganxmlusersfile.asp
If you want to know more about ASP.net security, refer to the Microsoft. NET Framework Developer ' s Guide Documentation:
asp.net security: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/ Cpconaspnetwebapplicationsecurity.asp
If you want to know more about System.Web.Security name space, please refer to:
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebSecurity.asp
If you want to know more about asp.net configuration, refer to the Microsoft. NET Framework Developer ' s Guide Documentation:
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 on ASP.net security guidance, please refer to MSDN:
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/authaspdotnet.asp
To learn more about ASP.net, refer to the MSDN newsgroups:
http://go.microsoft.com/fwlink/?linkid=5811&clcid=0x409

This article applies to:
Microsoft asp.net (included with the. NET Framework 1.1)
Microsoft Visual C #. NET (2003)
Microsoft asp.net (included with the. NET Framework) 1.0
Microsoft Visual C #. NET (2002)
Microsoft SQL Server Editions (all)
Microsoft SQL Server 7.0
Microsoft SQL Server 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.