In this article I will explain with example, how to implement simple Form based authentication using Login page and Login control in ASP.Net using C# and VB.Net.
The Form based authentication has been implemented using ASP.Net Membership Provider.
Database
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure to Validate the User Credentials
The following
Stored Procedure is used to validate the user credentials, it performs the following checks.
Case 1: If the UserName and Password are not correct else returns -1.
Case 2: If the UserName and Password are correct but the user has not been activated then the code returned is -2.
Case 3: If the UserName and Password are correct and the user account has been activated then UserId of the user is returned by the
Stored Procedure.
CREATE PROCEDURE [Validate_User]
@Username NVARCHAR(20),
@Password NVARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @UserId INT, @LastLoginDate DATETIME
SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
FROM Users WHERE Username = @Username AND [Password] = @Password
IF @UserId IS NOT NULL
BEGIN
IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
BEGIN
UPDATE Users
SET LastLoginDate = GETDATE()
WHERE UserId = @UserId
SELECT @UserId [UserId] -- User Valid
END
ELSE
BEGIN
SELECT -2 -- User not activated.
END
END
ELSE
BEGIN
SELECT -1 -- User invalid.
END
END
Pages
The program consists of two pages first Login page (Login.aspx) using which the user will logged in and second the Home page (Home.aspx) which is used when user will be redirected after successful authentication.
Login Page
HTML Markup
The following HTML Markup consists of:
Login control – For creating a login interface.
It has been assigned with the following event.
OnAuthenticate – For specifying the name of server-side method.
<asp:Login ID="userLogin" runat="server" OnAuthenticate="ValidateUser"></asp:Login>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web.Security
Validating the User Credentials
When the
Log In button is clicked, the UserName and Password values are fetched and passed to the Stored Procedure and
Stored Procedure is executed.
Then, the switch case is executed and if the UserId value is -1 or -2 then an appropriate message will be displayed.
If the UserName and Password are correct then the User is redirected to the Home page using RedirectFromLoginPage method of the FormsAuthentication class.
C#
protectedvoid ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string spName = "Validate_User";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = newSqlConnection(constr))
{
using (SqlCommand cmd = newSqlCommand(spName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", userLogin.UserName);
cmd.Parameters.AddWithValue("@Password", userLogin.Password);
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
switch (userId)
{
case -1:
userLogin.FailureText = "Username and/or password is incorrect.";
break;
case -2:
userLogin.FailureText = "Account has not been activated.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(userLogin.UserName, userLogin.RememberMeSet);
break;
}
}
}
VB.Net
ProtectedSub ValidateUser(sender AsObject, e AsEventArgs)
Dim userId AsInteger = 0
Dim spName AsString = "Validate_User"
Dim constr AsString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(spName, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Username", userLogin.UserName)
cmd.Parameters.AddWithValue("@Password", userLogin.Password)
con.Open()
userId = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
End Using
Select Case userId
Case -1
userLogin.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
userLogin.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(userLogin.UserName, userLogin.RememberMeSet)
Exit Select
End Select
End Using
End Sub
Home Page
HTML Markup
The following HTML Markup consists of following controls:
LoginName – For displaying the username of the currently logged-in user.
LoginStatus – For displaying login status information and perform logout functionality.
Welcome <asp:LoginName ID="LoginName" runat="server" Font-Bold="true" />
<br/><br/>
<asp:LoginStatus ID="LoginStatus" runat="server" />
Namespaces
You will need to import the following namespace.
C#
using System.Web.Security;
VB.Net
Imports System.Web.Security
Verify whether User has Logged In
Inside the Page_Load event handler, a check is performed whether the User is authenticated using the IsAuthenticated property.
If the user is not authenticated then he is redirected back to the Login page using RedirectToLoginPage method.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.Page.User.Identity.IsAuthenticated Then
FormsAuthentication.RedirectToLoginPage()
End If
End Sub
Screenshot
Downloads