How to use C # .NET in ASP.NET to implement a form-based verification

xiaoxiao2021-03-06  74

How to use C # .NET in ASP.NET to implement a form-based verification translation: MYDOTNET

This article quoted the following names in the Microsoft .Net library: system.data.sqlclient system.web.security ---------------------- ------- Task: Summary: 1. Requirements 2. Create an ASP.NET application 3 with Visual C # .NET. Configure security settings 4 in the web.config file. Create a database table sample to store user information 5. Create a Logon.aspx page 6. Write an event processing code to verify the user identity 7. Create a Default.aspx page 8. Additional Tips Reference Article ------------------------------- Abstract This article demonstrates how to achieve user information through data stock users Form-based verification. (1) The following tools are required to implement 1. Microsoft Visual Studio.net 2. Microsoft Internet Information Services (IIS) Version 5.0 or Update 3. Microsoft SQL Server (2) Create an ASP.NET application 1 with C # .NET 1. Open Visual Studio.net 2. Create a new ASP.NET web application and specify the name and path. (3) Configuring Security Settings in Web.config files This section demonstrates how to configure the ASP.NET application by adding and modifying and nodes to implement form-based authentication. 1. In the Solution window, open the web.config file. 2. Change the Authentication mode to Forms (Note: Default to Windows) 3. Insert the tag and fill in the appropriate properties. (Please link to the MSDN document listed in the article or the QuickStart document to see these properties) First copy the following code, then paste it to section:

(Note: If you do not specify LoginURL, default is default.aspx) 4. Reject anonymous access by adding the following node:

(4) Creating a database table sample to store user profile This section demonstrates how to create a sample database to store username, password, and user roles. If you want to implement role-based security, it is necessary to add a field that stores a user role in the database. 1. Open a notepad. 2. Copy the script below to Notepad and save:

IF exists (Select * from sysobjects where id = Object_id (n '[dbo]. [users]') And ObjectProperty (ID, n'susertable ') = 1) DROP TABLE [DBO]. [users] GOCREATE TABLE [DBO] NOT NULL, [PWD] [VARCHAR] (25) NOT NULL, [DBO] Goalter Table [DBO "NOT NULL, [VARCHAR]. ]. [Users] with nocheck address [pk_users] primary key nonclustered ([uname]) on [primary] GO

INSERT INTO USERS VALUES ('user1') 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 then paste the above scripts, run. At this time, create a sample user table that will be used in this sample program in the PUBS database. (5) Creating a Logon.aspx page 1. Create a new web form in the created item, named logon.aspx. 2. Open logon.aspx in the editor to switch to the HTML view. 3. Copy the following code and then "select Paste as an HTML" option in the Edit menu, insert it to the tag.

Logon Page
Email: < / TR>
Password: Persistent cookie:

This page is used to display a login form so that the user can provide their username and password and record it in the application. 4. Switch to the design view and save this page.

(6) Write an event processing code to verify that the code below the user 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 namespaces in the back code file: use system.data.sqlclient; use system.Web.security; 3. Create a ValidateUser function, verify the user's identity by finding the user in the database. (Please change your connection string to point to the 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 shouth. System.diagnostics.trace.writeline ("[ValidateUser] Exception" ex. measureage);

// if no password found, return false. If (null == lookpassword) {// you could write failed log for addressal security. Return false;}

// Compare Lookuppassword and INPUT Password, Using A Case-Sensitive Comparison. Return (0 == String.comPare (Lookuppassword, Password, false);

(Note: This code means that the input username and password are in line with a certain condition, as above, if it is connected to the database, and the password is removed according to the username and return password, the final code is determined whether the password is determined. It is empty, if it is not determined to determine the empty password and whether the input password is the same, the last FALSE parameter is not case sensitive.)

4. Use one of the following two methods in the CMDLogin_Serverlick event to generate a cookie of a form verification and go to the specified page. The sample code for two methods is provided below, and select it according to your needs. A) Call the RedirectFromLoginPage method in the CMDLogin_ServerClick event to prevent a table authentication cookie and direct the page to a specified page. Private void cmdlogin_serverclick (object sender, system.eventargs e) {if (validateuser (txtusername.value)

Formsauthentication.RedirectFromLoginPage (TxtuserName.Value, ChkpresistCookie.checked); else response.redirect ("logon.aspx", true);

}

b) Generate an encrypted verification ticket, create a reconciled cookie, and redirect users. This way gives more control to let you create a cookie, you can also contain some custom data along with the FormSauthenticationalTicket. private void cmdLogin_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 an authentication ticket cookiestr = FormsAuthentication.Encrypt (tkt); // and the encrypted ticket ck = new HttpCookie (FormsAuthentication.FormsCookieName, cookiestr); // create a cookie if (chkpersistCookie.Checked) // If the user chooses to save passwords ck.Expires = tkt.Expiratioin; // set the 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);} else Reponse.Redirect ( "logon .aspx ", true); T.ASPX Page This section creates a test page to redirect to the page when the user is verified. If the user is not recorded for the first time, navigate to this page, when the user will be redirected to the login page. 1. Rename the existing WebForm1.aspx as default.aspx and open it in the editor.

2. Switch to the HTML view, copy the following code to the tag: This button is used to log off the form verification session. 3. Switch to the design view, save the page. 4. Import the necessary namespace in the rear code: use system.Web.security; 5. Double-click the SINGOUT button to open the back code (default.aspx.cs), then copy the following code to cmdsingout_serverclick event processing: Private Void cmdSignOut_ServerClick (object sender, System.EventArgs e) {FormsAuthentication.SignOut (); // cancellation Response.Redirect ( "logon.aspx", true);} 6. Make sure the following code InititalizeComponent process: this.cmdSignOut. ServerClick = New System.EventHandler (this.cmdsignout_serverclick; 7. Save the compile project, now you can run this application. (8) Additional Tips 1. If you want to securely store your password in the database, you can encrypt the HashPasswordforStoringInfigFile function stored in the FormSauthentication class before storing data. (Note: A hash certificate will be generated 2. You can store SQL connection information in the configuration file (web.config) so that it is convenient to modify it when needed. 3. Can add some code to prevent hackers from using the exhaustive law to log in. For example, add some logic to enable users to have only two or three logins. If the user cannot log in in the specified login number, set a flag in the database to prevent the user from logging in until this user accesses another page or tells your help. Alternatively, some appropriate error processing can be added when needed. 4. Because the user is identified based on the authentication cookie, you can use a security socket layer (SSL) in the application to protect the authentication cookie and other useful information. 5. Requires the client's vault to accept or enable cookies. 6. The timeout parameter in the Configuration section is used to control the interval time of authentication of cookies. It can give it 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 reall back to another user. Because form-based verification is to verify users using cookies, the user can cause users to be accidentally mistaken to be used by the intermediary server or buffer.

Reference: If you want to know how to store your username and password by configuring Node, please refer to the following GotDotNET ASP.NET QuickStart example: Based on form-based authentication: http://www.gotdot.com.com /Quickstart/ASPLUS/default.aspx?url=/quickStart/ASPPLUS/doc/FormSAuth.aspx If you want to know how to use the XML file to store username and password to implement a form-based authentication, please refer to the following example of the SDK document: 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, please refer to Microsoft. NET Framework Developer's Guide Document: 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 For .Web.Security name space, please refer to: http://msdn.microsoft.com/library/default.asp? URL = / library / en-us / cpref / html / frfsystemWebsecurity.asp If you want to know more about If the ASP.NET configuration, please refer to Microsoft .NET Framework Developer's Guide Document: ASP.NET Configuration: http://msdn.microsoft.com/library/default.asp? URL = / library / en-US / CPGUIDE / HTML / CPConaspnetConfiguration.aspasp.net configuration node: http://msdn.microsoft.com/library/default.asp? url = / library / en-us / cpguide / h TML / CPGRFASPNETCONFIGURATIONSECTIONS.ASP If you want to know more about ASP.NET security guidance, please refer to MSDN: http://msdn.microsoft.com/library/default.asp? URL = / library / en-us / dnbda / html /AUTHASPDOTNET.ASP If you want to know more about ASP.NET, please refer to the MSDN newsgroup: http://go.microsoft.com/fwlink/? linkid = 5811 & clcid = 0x409

转载请注明原文地址:https://www.9cbs.com/read-120755.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.046, SQL: 9