惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
V
Vulnerabilities – Threatpost
GbyAI
GbyAI
P
Proofpoint News Feed
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
A
About on SuperTechFans
T
Tenable Blog
M
MIT News - Artificial intelligence
IT之家
IT之家
I
Intezer
D
DataBreaches.Net
爱范儿
爱范儿
T
Threatpost
C
CERT Recently Published Vulnerability Notes
云风的 BLOG
云风的 BLOG
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
K
Kaspersky official blog
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
Y
Y Combinator Blog
Cyberwarzone
Cyberwarzone
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
H
Help Net Security
Microsoft Security Blog
Microsoft Security Blog
Spread Privacy
Spread Privacy
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
AWS News Blog
AWS News Blog
博客园 - 聂微东
C
Check Point Blog
S
Securelist
有赞技术团队
有赞技术团队
雷峰网
雷峰网
aimingoo的专栏
aimingoo的专栏
Last Week in AI
Last Week in AI
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
D
Docker
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tailwind CSS Blog
L
Lohrmann on Cybersecurity
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LangChain Blog

博客园 - 豆浆

C#速成(之四) C#速成(之三) C#速成(之一) C#速成(之五)全文完 RegExp ASP后遗症种种 Visual SourceSafe如何支持并行开发 在 ASP.NET 中执行 URL 重写 New Security Features in ASP.NET 2.0 Storing User Information with ASP.NET 2.0 Profiles Take Advantage of ASP.NET Built-in Features to Fend Off Web Attacks (MS SQL Server)SQL语句导入导出大全 一个美国老工程师的心理话: 给年轻工程师的十大忠告 很强的c#.net函数列表 微软开发者系列讲座下载 国产软件陷入3大争论 反垄断法出台迫在眉睫 国内软件业陷入“三输”怪圈 正走向慢性自杀 联想欲借自主知识产权操作系统“麒麟”挺直腰杆 今年中国“十大并购
How To Implement Forms-Based Authentication in Your ASP.NET Application by Using C# .NET
豆浆 · 2005-03-13 · via 博客园 - 豆浆

http://support.microsoft.com/kb/301240/EN-US/

Article ID : 301240
Last Review : June 29, 2004
Revision : 5.1

This article was previously published under Q301240

For a Microsoft Visual Basic .NET version of this article, see 308157.

This article refers to the following Microsoft .NET Framework Class Library namespaces:

System.Data.SqlClient
System.Web.Security

IN THIS TASK

On this page

SUMMARY

This article demonstrates how to implement forms-based authentication by using a database to store the users.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:

Microsoft Visual Studio .NET
Microsoft Internet Information Services (IIS) version 5.0 or later
Microsoft SQL Server

back to the top

Create an ASP.NET Application Using C# .NET

1. Open Visual Studio .NET.
2. Create a new ASP.NET Web application, and specify the name and location.

back to the top

Configure the Security Settings in the Web.config File

This section demonstrates how to add and modify the <authentication> and <authorization> configuration sections to configure the ASP.NET application to use forms-based authentication.

1. In Solution Explorer, open the Web.config file.
2. Change the authentication mode to Forms.
3. Insert the <Forms> tag, and fill the appropriate attributes. (For more information about these attributes, refer to the MSDN documentation or the QuickStart documentation that is listed in the REFERENCES section.) Copy the following code, and then click Paste as HTML on the Edit menu to paste the code in the <authentication> section of the file:
<authentication mode="Forms">
   <forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx"
   protection="All" path="/" timeout="30" />
</authentication>
                              
4. Deny access to the anonymous user in the <authorization> section as follows:
<authorization>
   <deny users ="?" />
   <allow users = "*" />
</authorization>
                              

back to the top

Create a Sample Database Table to Store Users Details

This section demonstrates how to create a sample database to store the user name, password, and role for the users. You need the role column if you want to store user roles in the database and implement role-based security.

1. On the Start menu, click Run, and then type notepad to open Notepad.
2. Highlight the following SQL script code, right-click the code, and then click Copy. In Notepad, click Paste on the Edit menu to paste the following code:
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. Save the file as Users.sql.
4. On the Microsoft SQL Server computer, open Users.sql in Query Analyzer. From the list of databases, click pubs, and run the script. This creates a sample users table and populates the table in the Pubs database to be used with this sample application.

back to the top

Create a Logon.aspx Page

1. Add a new Web Form to the project named Logon.aspx.
2. Open the Logon.aspx page in the editor, and switch to HTML view.
3. Copy the following code, and use the Paste as HTML option on the Edit menu to insert the code between the <form> tags:
<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="cmdLogin"><p></p>
<asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" />
                                    
This Web Form is used to present a logon form to users so that they can provide their user name and password to log on to the application.
4. Switch to Design view, and save the page.

back to the top

Code the Event Handler So That It Validates the User Credentials

This section presents the code that is placed in the code-behind page (Logon.aspx.cs).

1. Double-click Logon to open the Logon.aspx.cs file.
2. Import the required namespaces in the code-behind file:
using System.Data.SqlClient;
using System.Web.Security;
                              
3. Create a ValidateUser function to validate the user credentials by looking in the database. (Make sure that you change the 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 should 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 could 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 ) );

}
                              
4. You can use one of two methods to generate the forms authentication cookie and redirect the user to an appropriate page in the cmdLogin_ServerClick event. Sample code is provided for both scenarios. Use either of them according to your requirement.
Call the RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an 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 the authentication ticket, encrypt it, create a cookie, add it to the response, and redirect the user. This gives you more control in how you create the cookie. You can also include custom data along with the FormsAuthenticationTicket in this case.
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;
                ck.Path = FormsAuthentication.FormsCookiePath;
      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);
}
                                    
5. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);
                              

back to the top

Create a Default.aspx Page

This section creates a test page to which users are redirected after they authenticate. If users browse to this page without first logging on to the application, they are redirected to the logon page.

1. Rename the existing WebForm1.aspx page as Default.aspx, and open it in the editor.
2. Switch to HTML view, and copy the following code between the <form> tags:
<input type="submit" Value="SignOut" runat="server" id="cmdSignOut">
                                    
This button is used to log off the forms authentication session.
3. Switch to Design view, and save the page.
4. Import the required namespaces in the code-behind file:
using System.Web.Security;
                              
5. Double-click SignOut to open the code-behind page (Default.aspx.cs), and copy the following code in the cmdSignOut_ServerClick event handler:
private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
{
   FormsAuthentication.SignOut();
   Response.Redirect("logon.aspx", true);
}
                              
6. Make sure that the following code is added to the InitializeComponent method in the code that the Web Form Designer generates:
this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);
                              
7. Save and compile the project. You can now use the application.

back to the top

Additional Notes

You may want to store passwords securely in a database. You can use the FormsAuthentication class utility function named HashPasswordForStoringInConfigFile to encrypt the passwords before you store them in the database or configuration file.
You may want to store the SQL connection information in the configuration file (Web.config) so that you can easily modify it if necessary.
You may consider adding code to prevent hackers who try to use different combinations of passwords from logging on. For example, you can include logic that accepts only two or three logon attempts. If the user cannot log on in a certain number of attempts, you may want to set a flag in the database to not allow that user to log on until that user re-enables his or her account by visiting a different page or by calling your support line. In addition, you should add appropriate error handling wherever necessary.
Because the user is identified based on the authentication cookie, you may want to use Secure Sockets Layer (SSL) on this application so that no one can deceive the authentication cookie and any other valuable information that is being transmitted.
Forms-based authentication requires that your client accept or enable cookies on their browser.
The timeout parameter of the <authentication> configuration section controls the interval at which the authentication cookie is regenerated. You can choose a value that provides better performance and security.
Certain intermediary proxies and caches on the Internet may cache Web server responses that contain Set-Cookie headers, which are then returned to a different user. Because forms-based authentication uses a cookie to authenticate users, this can cause users to accidentally (or intentionally) impersonate another user by receiving a cookie from an intermediary proxy or cache that was not originally intended for them. The following article explains how to combat these situations:

263730 Site Server Users May Be Authenticated Under the Wrong Account

back to the top

REFERENCES

For more information about how to implement simple forms-based authentication that uses the <credentials> section to store users and passwords, refer to the following GotDotNet ASP.NET QuickStart sample:

For more information about how to implement forms-based authentication that uses an XML file to store users and passwords, refer to the following topic in the .NET Framework Software Development Kit (SDK) documentation:

For more information about ASP.NET Web application security, refer to the following Microsoft .NET Framework Developer's Guide documentation:

For more information about the System.Web.Security namespace, refer to the following Microsoft .NET Framework Reference documentation:

For more information about ASP.NET configuration, refer to the following Microsoft .NET Framework Developer's Guide articles:

For information about the ASP.NET security guidelines, refer to the following MSDN white paper:

For more general information about ASP.NET, refer to the following MSDN newsgroup:

back to the top


APPLIES TO
Microsoft ASP.NET 1.1
Microsoft Visual C# .NET 2003 Standard Edition
Microsoft ASP.NET 1.0
Microsoft Visual C# .NET 2002 Standard Edition
Microsoft SQL Server 2000 Standard Edition
Microsoft SQL Server 7.0 Standard Edition
Microsoft SQL Server 2000 64-bit Edition
Keywords: 
kbhowtomaster kbweb kbsecurity kbconfig KB301240