Forms Authentication Using SQL - Part 1
page 4 of 4
by Jason N. Gaylord
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 42958/ 68

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:
Login.aspx
**************************************************

1:    <%@ Import Namespace="System.Data" %>
2:    <%@ Import Namespace="System.Data.SqlClient" %>
3:    
4:    <Script Runat="Server">
5:    
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
13:   
14:      Function MyAuthentication(strUsername As String, _ 
15:        strPassword As String) As Integer
16:   
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
23:   
24:         ' Set conn equal to the conn. string we setup in the web.config
25:         conn = ConfigurationSettings.AppSettings("conn")
26:         myConn = New SQLConnection(conn)
27:      
28:         ' We are going to use the stored procedure setup earlier
29:         myCmd = New SQLCommand("MyAuthentication",myConn)
30:         myCmd.CommandType = CommandType.StoredProcedure
31:   
32:         ' Set the default return parameter
33:         myReturn = myCmd.Parameters.Add("RETURN_VALUE",SqlDbType.Int)
34:         myReturn.Direction = ParameterDirection.ReturnValue
35:   
36:         ' Add SQL Parameters
37:         myCmd.Parameters.Add("@username",strUsername)
38:         myCmd.Parameters.Add("@password",strPassword)
39:      
40:         ' Open SQL and Execute the query
41:         ' Then set intResult equal to the default return parameter
42:         ' Close the SQL connection
43:         myConn.Open()
44:            myCmd.ExecuteNonQuery()
45:            intResult = myCmd.Parameters( "RETURN_VALUE" ).Value
46:      myConn.Close()
47:   
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>"
53:            Else
54:               lblMessage.Text = "Invalid Password!<br><br>"
55:            End If
56:         End If
57:   
58:         ' Return the userid
59:         Return intResult
60:   
61:      End Function
62:   
63:   </Script>
64:   
65:   <html>
66:   
67:   <head>
68:      <title>Authentication Sample</title>
69:   </head>
70:   
71:   <body>
72:      <form Runat="Server">
73:         <asp:table runat="Server" HorizontalAlign="Center">
74:            <asp:tablerow>
75:               <asp:tablecell ColumnSpan="2">
76:                  <h2>Please Login:</h2>
77:                  <asp:label ID="lblMessage" ForeColor="Crimson" Font-Bold="True" 
                      Runat="Server" />
78:               </asp:tablecell>
79:            </asp:tablerow>
80:            <asp:tablerow>
81:               <asp:tablecell CssClass="FormText">
82:                  <b>Username:</b>   
83:               </asp:tablecell>
84:               <asp:tablecell CssClass="FormText">
85:                  <asp:TextBox ID="txtUsername" MaxLength="25" Runat="Server"
                      CssClass="FormElement" />
86:                    
87:                  <asp:RequiredFieldValidator ControlToValidate="txtUsername"
                      Text="Required!" Runat="Server" />
88:               </asp:tablecell>
89:            </asp:tablerow>
90:            <asp:tablerow>
91:               <asp:tablecell CssClass="FormText">
92:                  <b>Password:</b>   
93:               </asp:tablecell>
94:               <asp:tablecell CssClass="FormText">
95:                  <asp:TextBox ID="txtPassword" TextMode="Password" 
                      MaxLength="25" Runat="Server" CssClass="FormElement" />
96:                    
97:                  <asp:RequiredFieldValidator ControlToValidate="txtPassword"
                      Text="Required!" Runat="Server" />
98:               </asp:tablecell>
99:            </asp:tablerow>
100:            <asp:tablerow>
101:               <asp:tablecell ColumnSpan="2">
102:                  <br>
103:                  <asp:Button Text="Login!" OnClick="Login_Click" 
                      Runat="Server" />
104:               </asp:tablecell>
105:            </asp:tablerow>
106:         </asp:table>
107:      </form>
108:   </body>
109:   
110:   </html&gl;

The html contains a form with three basic elements: a username field, a password field, and a login button. RequiredFieldValidator controls were used to make sure the username and password fields were completed before submit. These controls use javascript templates found in a directory under your web root called aspnet_client. If you do not have this folder, you must copy and rename the folder called ASP.NETClientFiles under your C:\{Windows Root}\Microsoft.NET\Framework\{Framework Version} folder to the root of your web (usually c:\inetpub\wwwroot).

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.

View Entire Article

User Comments

Title: c# code   
Name: raj
Date: 5/25/2011 7:51:10 AM
Comment:
Hi I want the code in C#, can u please send it?
Title: login authentication in asp.net   
Name: khyati
Date: 7/13/2009 1:09:45 AM
Comment:
very good!
Title: Good stuff   
Name: jes
Date: 4/16/2007 3:31:45 AM
Comment:
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
Title: Nice done but...   
Name: Edgar
Date: 9/12/2006 4:25:17 PM
Comment:
I just have a little question. What if i want to know the username of the user in other wepages???.
Title: good   
Name: ANTONY LEO EDEL
Date: 3/27/2006 5:40:52 AM
Comment:
easy to understand . lot of thanks
Title: Woooow   
Name: Eryk
Date: 2/2/2006 4:50:17 PM
Comment:
Very Very Good.
Title: very good   
Name: Tuncay
Date: 1/14/2006 2:20:40 AM
Comment:
thanks, this tutorial is very good.
Title: RE:   
Name: Bryan
Date: 11/15/2005 3:46:14 PM
Comment:
Convert sqlCommand2.Parameters["RETURN_VALUE"].Value to a integer
Title: a question!   
Name: mohammad
Date: 11/12/2005 10:15:36 AM
Comment:
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#?
Title: excellent   
Name: jh
Date: 10/3/2005 5:21:58 PM
Comment:
very nice work - thanks much!
Title: need an import though   
Name: jh
Date: 10/3/2005 5:14:52 PM
Comment:
it neededs this at the top of the page though:

Imports System.Web.Security
Title: Perfect   
Name: Jacques
Date: 7/29/2005 4:49:45 AM
Comment:
Thank you. Just what i needed.
Title: WellDone   
Name: Man
Date: 6/16/2005 10:29:39 PM
Comment:
This was very well done and cover a whole lit of stuff that I actually was after!

Thanks!
Title: Gant   
Name: Gant Man
Date: 5/28/2005 11:30:31 PM
Comment:
Thanks

Just what I was after
Title: Good   
Name: Majun
Date: 2/10/2005 2:56:41 AM
Comment:
Very Good.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 9/1/2014 9:48:33 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search