06 Oct 2003
This article provides some basic code to set up forms authentication within your web.
Tested: ASP.NET 1.0
This article has not yet been rated.|
Views (Total / Last 10 Days):
Have you ever wondered how sites authenticate users using forms? This article will explain how to by using ASP.Net and SQL 2000.
First, you need to prepare your computer to run the authentication. Be sure you already have IIS installed and running on a Windows 2000 (or better) computer or server. You also need to install the .Net Framework which is a free download available from Microsoft. After the .Net Framework is installed, you must configure IIS to run the framework properly. You can do so by going to IIS and setting the default user to ASPNET. More experienced users might want to edit the config files on the host to add additional users or permissions.
Secondly, you need to establish a database in SQL. If you do not have SQL, the SQL desktop engine (MSDE) is available as a free download from Microsoft. You can download this engine by going to www.asp.net/webmatrix/ and downloading the ASP.Net Community built Web Matrix. This will include steps to downloading MSDE. Once you have downloaded and installed your MSDE, you must setup a database.
|Section 1: Setting up SQL|
At this point, all of the necessary work has been done to establish the base of your project. Then create a table and procedure to hold and query users and passwords. For this example, I used the following:
1: CREATE TABLE [dbo].[User] (
2: username char(25),
3: password char(25),
7: CREATE PROCEDURE MyAuthentication
10: @username Char( 25 ),
11: @password Char( 25 )
15: DECLARE @actualPassword Char( 25 )
18: @actualPassword = Password
19: FROM [Users]
20: Where username = @username
22: IF @actualPassword IS NOT NULL
23: IF @password = @actualPassword
24: RETURN 1
26: RETURN -2
28: RETURN -1
The table called users holds the username and passwords of visitors. The procedure called MyAuthentication is the gateway to the table users. It allows 2 parameters to be passed, username and password. The procedure then queries the table for entries where the passed username (@username) is equal to the username in the table (username). The If..Else statement works similar to any other programming if..else statement. If no results are returned from the select statement, the procedure will return a -1. If results are returned, the next If..Else statement is executed. This statement checks to see if the passed password (@password) is equal to the actual password in the table (@actualPassword). If it is, 1 is returned. Otherwise, a -2 will be returned.
|Section 2: Setting Up The Web.Config File|
Now that the SQL side is setup, we can begin programming the ASP.Net pages. We will begin by configuring our web application. The configuration is stored in a file called web.config. A sample of the configuration is shown below:
4: <!-- This section stores your SQL configuration as an appsetting called
5: conn. You can name this setting anything you would like.
8: <add key="conn" _
9: value="server=localhost;database=MySite;uid=sa;pwd=password;" />
13: <!-- This section sets the authentication mode to forms authentication
14: and routes all traffic to the specified page. It also specifies a
15: timeout. The authorization section below denies all users not
16: authenticated. For testing purposes, custom errors was turned off.
17: The section below allows pages to be trace enabled for debugging
21: <authentication mode="Forms">
22: <forms name="MyFormsAuthentication" loginUrl="login.aspx" _
23: protection="All" timeout="720" />
27: <deny users="?" />
30: <customErrors mode="Off" />
32: <trace enabled="true" requestLimit="0" pageOutput="true" />
This will setup the basic web.config file that we will need.
|Section 3: Creating The ASP.NET Page|
The login ASP.Net page will include two sections, a code block and an html block. For my example, I used the following login page:
1: <%@ Import Namespace="System.Data" %>
2: <%@ Import Namespace="System.Data.SqlClient" %>
4: <Script Runat="Server">
6: Sub Login_Click( s As Object, e As EventArgs )
7: If IsValid Then
8: If MyAuthentication(txtUsername.Text,txtPassword.Text) > 0 Then
9: FormsAuthentication.RedirectFromLoginPage (txtUsername.Text,False)
10: End If
11: End If
12: End Sub
14: Function MyAuthentication(strUsername As String, _
15: strPassword As String) As Integer
17: ' Variable Declaration
18: Dim myConn As SQLConnection
19: Dim myCmd As SQLCommand
20: Dim myReturn As SQLParameter
21: Dim intResult As Integer
22: Dim conn As String
24: ' Set conn equal to the conn. string we setup in the web.config
25: conn = ConfigurationSettings.AppSettings("conn")
26: myConn = New SQLConnection(conn)
28: ' We are going to use the stored procedure setup earlier
29: myCmd = New SQLCommand("MyAuthentication",myConn)
30: myCmd.CommandType = CommandType.StoredProcedure
32: ' Set the default return parameter
33: myReturn = myCmd.Parameters.Add("RETURN_VALUE",SqlDbType.Int)
34: myReturn.Direction = ParameterDirection.ReturnValue
36: ' Add SQL Parameters
40: ' Open SQL and Execute the query
41: ' Then set intResult equal to the default return parameter
42: ' Close the SQL connection
45: intResult = myCmd.Parameters( "RETURN_VALUE" ).Value
48: ' If..then..else to check the userid.
49: ' If the intResult is less than 0 then there is an error
50: If intResult < 0 Then
51: If intResult = -1 Then
52: lblMessage.Text = "Username Not Registered!<br><br>"
54: lblMessage.Text = "Invalid Password!<br><br>"
55: End If
56: End If
58: ' Return the userid
59: Return intResult
61: End Function
68: <title>Authentication Sample</title>
72: <form Runat="Server">
73: <asp:table runat="Server" HorizontalAlign="Center">
75: <asp:tablecell ColumnSpan="2">
76: <h2>Please Login:</h2>
77: <asp:label ID="lblMessage" ForeColor="Crimson" Font-Bold="True"
81: <asp:tablecell CssClass="FormText">
84: <asp:tablecell CssClass="FormText">
85: <asp:TextBox ID="txtUsername" MaxLength="25" Runat="Server"
87: <asp:RequiredFieldValidator ControlToValidate="txtUsername"
Text="Required!" Runat="Server" />
91: <asp:tablecell CssClass="FormText">
94: <asp:tablecell CssClass="FormText">
95: <asp:TextBox ID="txtPassword" TextMode="Password"
MaxLength="25" Runat="Server" CssClass="FormElement" />
97: <asp:RequiredFieldValidator ControlToValidate="txtPassword"
Text="Required!" Runat="Server" />
101: <asp:tablecell ColumnSpan="2">
103: <asp:Button Text="Login!" OnClick="Login_Click"
The server button contains an OnClick method that calls a subroutine called Login_Click. The Login_Click subroutine checks the validity of the form and then checks to be sure the authentication was validated. If it was, the form will redirect the user to the page that forwarded the request to the login.aspx page. If not, the user will remain on the page until the credentials are correct.
The authentication is checked using a function called MyAuthentication. This function calls the SQL settings from the web.config file. It then declares that a stored procedure will be used. Finally, input and return parameters are added to the procedure declaration. When the stored procedure is executed, the return value is checked for errors. Remember that our stored procedure returns a negative number for an incorrect username or password. The If..Else statement is setup to check this. If the credentials are incorrect, a message will be displayed on the screen. If they are correct, the function will return a positive value and continue in the subroutine.
5/25/2011 7:51:10 AM
Hi I want the code in C#, can u please send it?
login authentication in asp.net
7/13/2009 1:09:45 AM
4/16/2007 3:31:45 AM
I got an error in this line
intResult = myCmd.Parameters( "RETURN_VALUE" ).Value
when i converted the code to c#.error is
intResult = myCmd.Parameters( "RETURN_VALUE" ).Value
how do i solve this
Nice done but...
9/12/2006 4:25:17 PM
I just have a little question. What if i want to know the username of the user in other wepages???.
ANTONY LEO EDEL
3/27/2006 5:40:52 AM
easy to understand . lot of thanks
2/2/2006 4:50:17 PM
Very Very Good.
1/14/2006 2:20:40 AM
thanks, this tutorial is very good.
11/15/2005 3:46:14 PM
Convert sqlCommand2.Parameters["RETURN_VALUE"].Value to a integer
11/12/2005 10:15:36 AM
hello ,thanx for this grat code ,but i have a prob!!
i have converted this code to C# and every thing is fine exept this statment
ntResult = sqlCommand2.Parameters["RETURN_VALUE"].Value;
it say can nit implicit convert from in to object ,
so can u help me in doning it in c#?
10/3/2005 5:21:58 PM
very nice work - thanks much!
need an import though
10/3/2005 5:14:52 PM
it neededs this at the top of the page though:
7/29/2005 4:49:45 AM
Thank you. Just what i needed.
6/16/2005 10:29:39 PM
This was very well done and cover a whole lit of stuff that I actually was after!
5/28/2005 11:30:31 PM
Just what I was after
2/10/2005 2:56:41 AM