How to implement Forms Authentication in ASP.NET?

Whether in a banking application or a job portal every where we required to authenticate user before allowing access. Or else Spam user can destroy our properties. In the login mechanism of ASP.NET using Form Authentication we can validate an user. During Forms Authentication ASP.NET authenticates user and maintains authentication token in a cookie for next consecutive actions. During page request the cookie travels with URL. In a ASP.NET page cycle Form Authentication participate through the FormsAuthenticationModule class.

To implement Form Authentication first you required to update you web.config file with the following line of Codes. In forms tag set loginUrl property value to Login page file path. Then to block anonymous users from unknown login set Authorization to deny All. Syntax for deny all is <deny users=”?” />.


<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".lgnConfig">
<deny users="?" />

In Login.aspx after validating user credentials, redirecting the logged user to default page using “RedirectFromLoginPage” method.


<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>

<script runat="server">
Sub Login_Click(ByVal sender As Object, ByVal e As EventArgs)
If ((txtEmailID.Text = "") And _
(UserPass.Text = "raghavi")) Then
FormsAuthentication.RedirectFromLoginPage _
(txtEmailID.Text, chkRemember.Checked)
lblMsg.Text = "Invalid credentials. Please try again."
End If
End Sub

<head id="Head1" runat="server">
<title>Exmple of Forms Authentication</title>
<form id="frmLogin" runat="server">
<h3>User Login Page</h3>
<div>E-mail ID</div>
<div><asp:TextBox ID="txtEmailID" runat="server" /><asp:RequiredFieldValidator ID="rfEmailID" ControlToValidate=" txtEmailID" Display="Dynamic" ErrorMessage="Empty values are not allow." runat="server" /><div>

<div><asp:TextBox ID="txtPassword" TextMode="Password" runat="server" /><asp:RequiredFieldValidator ID="rfPassword" ControlToValidate="txtPassword" ErrorMessage=" Empty values are not allow." runat="server" />

<div><asp:CheckBox ID="chkRemember" runat="server" />&nbsp;Remember for Next Login</div>
<div><asp:Button ID="btnLogin" OnClick="Login_Click" Text="Log in" runat="server" /></div>
<div><asp:Label ID="lblMsg" ForeColor="red" runat="server" /></div>

Once user is at default page, In default page provided Signout button. Which destroys authenticated cookie using FormsAuthentication.SignOut method.


<%@ Page Language="VB" %>
<title>Successful Forms Authentication</title>

<script runat="server">
Sub Page_Load(ByVal Src As Object, ByVal e As EventArgs)
lblWelcomeMsg.Text = "Welcome, " & Context.User.Identity.Name
End Sub

Sub Signout_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub

<h3>Example of Forms Authentication</h3>
<asp:Label ID="lblWelcomeMsg" runat="server" />
<form id="frmDefault" runat="server">
<asp:Button ID="btnSignOut" OnClick="Signout_Click" Text="Sign Out" runat="server" /><p>