Form-based authentication in ASP.NET applications

zhaozj2021-02-16  70

How to: use C # to implement form-based authentication in your ASP.NET application (Q301240)

The content discussed herein belongs to:

Microsoft ASP.NET (including .NET Framework) Microsoft Visual C # .NET (2002) Microsoft SQL Server 2000 (all versions) Microsoft SQL Server version 7.0

If you need to see the Microsoft Visual Basic .NET version of this article, see

Q308157.

This article quoted the namespace of the following Microsoft .NET framework class library:

System.Data.sqlclient system.web.security

Herein

Overview Needs Use Visual C # .NET to create an ASP.NET application to modify security settings in Web.config to create a database table to store user details to create a logon.aspx file to add event response code to verify the user to create a default.aspx File Note Reference

Overview

This article describes how to implement a form-based authentication by using a data inventory storage user information.

return

demand

The following is the recommended soft, hardware and network environment:

Microsoft Visual Studio .NET Microsoft Internet Information Server (IIS) version 5.0 above Microsoft SQL Server

return

Built a ASP.NET application using Visual C # .NET

Open Visual Studio .NET. Click the File menu to select a new project. Create a new ASP.NET web application and specify the location and name.

return

Modify security settings in Web.config

This paragraph describes how to add, modify

with

The information between the ASP.NET app is set to use a form-based user authentication.

In the project browser, open the web.config file. in

Change the authentication mode in the attribute for Forms: mode = "forms"

Post-insert

Tags and fill in the appropriate properties. (To get more information about these attributes, see the MSDN document, or see the quick start document listed later in this article.) Copy the code below, and click "Endml Paste" in the "Edit" menu. Option, paste this code into the file

Segment:

in

During the segment, add code to refuse anonymous access, as shown below:

return

Create a database table to store user details

This paragraph mainly introduces how to create a simple database to store username, password, and user role. You need a role to store the user's role information to achieve a role-based security system.

In the Windows "Start" menu, click "Run" and enter "Notepad" to open the Word board. Select the following SQL script code, right click on this code, then click "Copy". In the Word board, click the "Paste" option in the Edit menu to paste the following code:

IF exists (Select * from sysobjects where id = Object_id (n '[dbo]) and ObjectProperty (ID, n'susertable') = 1) DROP TABLE [DBO]. [users] Go Create Table [DBO ]. [User] [VARCHAR] (15) Not null, [PWD] [VARCHAR] (25) Not Null, [Userrole] [varchar] (25) Not null,) on [primary] Go alter table [dbo]. [user] 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 ​​Saves files as user.sql. Use the machine installed Microsoft SQL Server, open the script User.sql just established in Query Analyzer. In the database list in the toolbar, select the database "PUBS" and then execute this script. This code in the script establishes a simple user table and adjusts the table in the database PUBS to the format that can be used in this sample application.

return

Create a logon.aspx file

Add a web form to the project and name Logon.aspx. Copy the code below, and click "As the HTML Paste" option in the "Edit" menu, paste this code into the file.

return

Add event response code to verify users

This paragraph introduces the code in the Code-BEHIND page corresponding to the login interface (Logon.aspx.cs).

Double-click the "Logon button" to open the logon.aspx.cs file. Import the required namespaces in this file:

Using system.data.sqlclient; using system.web.security;

Create a ValidateUser function to verify the user's identity by looking for methods in the database. (Make sure you change the connection string to point to your database)

private bool ValidateUser (string uid, string passwd) {SqlConnection cnn; SqlCommand cmd; SqlDataReader dr; cnn = new SqlConnection ( "server = localhost; uid = sa; pwd = password; database = pubs"); cmd = new SqlCommand ( " Select * from users where unam = '" uid "' ", cnn); cnn.open (); dr = cmd.executeReader (); while (tring.com ()) {if (string.compare (DR" "PWD"]. Tostring (), passwd, false == 0) {cnn.close (); return true;}} cnn.close (); Return False;} You can use one of the following two ways to generate Certified cookies and redirect users to the appropriate page in the CMDLogin_ServerClick event. We provide sample code for two ways, you can use any of them based on the needs.

Call the RedirectFromLoginPage method to generate an authentication cookie of a form and redirect the user to the appropriate page in the CMDLogin_ServerClick event:

private void cmdLogin_ServerClick (object sender, System.EventArgs e) {if (ValidateUser (txtUserName.Value, txtUserPass.Value)) FormsAuthentication.RedirectFromLoginPage (txtUserName.Value, chkPersistCookie.Checked); else Response.Redirect ( "logon.aspx", True);

Generate a authentication token and encrypt it, build a cookie with encryption results, and add it to the Response's cookies, and finally redirects the page. Using this method, you can get more control over how to create a cookie, you can also include some custom data in 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"); cookiestr = FormsAuthentication.Encrypt (tkt); ck = new HttpCookie (FormsAuthentication.FormsCookieName, cookiestr); if (chkPersistCookie.Checked) ck. Expires = tkt.Expiration; Response.Cookies.Add (ck); string strRedirect; strRedirect = Request [ "ReturnUrl"]; if (strRedirect == null) strRedirect = "default.aspx"; Response.Redirect (strRedirect, true) Else Response.Redirect ("Logon.aspx", true);} Please confirm that the following code has been added to the initializationComponent function generated by the form designer:

This.cmdlogin.serverClick = new system.eventhandler (this.cmdlogin_serverclick);

return

Create a default.aspx file

This section establishes a test page, and the user will be redirected to this page after authentication. If the user does not have prior login, try to access this page, they will be redirected to the login page.

Rename the already existing WebForm1.aspx page is default.aspx and open in the editor. Switch to the "HTML" view and copy the following code to the middle of the label:

This button will be used to log out of the certified session. Switching "Design" view and save the page. Import the namespace required in the Code-Behind page:

Using system.web.security;

Double-click Signout to open the Code-BEHIND page (default.aspx.cs) and copy the following code to the cmdsignout_serverClick event response function:

Private void cmdsignout_serverclick (object sender, system.eventargs e) {formsauthentication.signout (); response.Redirect ("logon.aspx", true);}

Make sure the following code is added to the initializationComponent function generated by the form designer:

THIS.CMDSIGNOUT.SERVERCLICK = New System.EventHandler (this.cmdsignout_serverclick);

Save and compile the project. You can now use this application now.

return

Note note

You may want to store passwords safely in the data. You can use the HashPasswordforStoringInfigfile function in the FormSauthentication class tool to encrypt it before you store your password. You may want to store SQL connection information into the web.config so you can easily modify it when you need it. If you consider adding some code to prevent hackers from using a different password combination trying to log in. You can limit the number of logins (for example, 2-3 times) in your code. If a user is not logged in several times, it is also possible to block the user from logging in by setting a flag in the database until he reactivates the account with other pages or hit your service support hotline. In addition, it should be considered to appropriately increase the error handling function as necessary. Since the user is based on the authentication cookie, you may want to use Secure Sockets Layer (SSL) in your app, so that no one can spoof the certification cookie. Form-based authentication requires you to enable on the client and allow you to use cookies. The set Timeout parameter controls the time interval generated by the authentication cookie, you can choose a parameter value to achieve good performance and security. Some intermediate agents and caches on the Internet may cache a web server response containing the cookie set head, which will then return to different users. Because of a form-based authentication, the user can authenticate the user, the consequence of the user can obtain the cookie, unintentional (or intentional) mimic other users from the intermediate agent or cache. The following article explains how to solve this problem.

Q263730 Site Server Uses May Be Authenticated Under The Wrong Account

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

New Post(0)