System TipThis article applies to a different operating system than the one you are using. Article content that may not be relevant to you is disabled.
This article was previously published under Q301240
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.
In Solution Explorer, open the Web.config file.
Change the authentication mode to Forms.
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:
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.
On the Start menu, click
Run, and then type notepad to open
Notepad.
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
Save the file as Users.sql.
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.
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).
Double-click Logon to open the
Logon.aspx.cs file.
Import the required namespaces in the code-behind file:
using System.Data.SqlClient;
using System.Web.Security;
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 ) );
}
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:
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);
}
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);
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.
Rename the existing WebForm1.aspx page as Default.aspx, and
open it in the editor.
Switch to HTML view, and copy the following code between
the <form> tags:
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.
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: