Forms Authentication in ASP.NET with an example

This post talks about one of the four types of Authentication system available in ASP.NET.

The forms authentication ticket is usually contained inside a cookie. Forms authentication processing is handled by the FormsAuthenticationModule class, which is an HTTP module that participates in the regular ASP.NET page processing cycle.

Forms authentication in ASPNET #authentication #aspnet #dotnet Click To Tweet

These are the following aspects of implementing security in asp.net web application.

Authentication

It is the process of ensuring the user’s identity and authenticity. ASP.NET allows four types of authentication system:

  1. Windows Authentication
  2. Forms Authentication
  3. Passport Authentication
  4. Custom Authentication

Authorization

It is the process of defining and allotting specific roles to specific users.

Confidentiality

It involves encrypting the channel between the client’s browser and the web server.

Integrity

It involves maintaining the integrity of data. For example, implementing digital signature.

Forms Authentication in ASP.NET

Below are the respective .aspx and .cs code files along with settings to be made in web.config.

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FormsAuthentication.Default" %>
 
    <!DOCTYPE html>
 
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link href="css/structure.css" rel="stylesheet" />
 
        <script type="text/javascript">

        </script>
 
    </head>
 
    <body>
 
        <form id="form1" runat="server" class="box login" defaultbutton="btnGo">
 
            <div class="boxBody">
 
                <div class="login_area">
 
                    <div>
 
                        <label>Username</label>
 
                        <asp:TextBox ID="txtUserName" runat="server" CssClass="username" MaxLength="20"></asp:TextBox>
 
                    </div>
 
                    <div>
 
                        <label>Password</label>
 
                        <asp:TextBox ID="txtPassword" runat="server" CssClass="password" TextMode="Password" MaxLength="15"></asp:TextBox>
 
                    </div>
 
                    <div class="go_botton" id="dvBtn">
 
                        <asp:Button ID="btnGo" Text="Login" class="btnLogin" onmousedown="mousedwnevt();" onmouseup="mouseupevt();" runat="server" OnClientClick="pageValid(event);" OnClick="btnLogin_Click" />
 
                    </div>
 
                </div>
 
            </div>
 
        </form>
 
    </body>
 
    </html>

Javascript code to be inserted before </head>


            function pageValid(e) {

                var obj = document.getElementById('txtUserName');

                if (obj.value == '') {

                    alert('Please enter username.');

                    obj.focus();

                    window.event ? event.returnValue = false : e.preventDefault();

                    return;

                }

                obj = document.getElementById('txtPassword');

                if (obj.value == '') {

                    alert('Please enter password.');

                    obj.focus();

                    window.event ? event.returnValue = false : e.preventDefault();

                    return;

                }

            }


Login.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FormsAuthentication
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string userName = txtUserName.Text.Trim();
            string password = txtPassword.Text.Trim();
            string clientIP = Request.UserHostAddress;
            DateTime loginDate = DateTime.Now;
            string userAgent = Request.Browser.Browser + "-" + Request.Browser.Version;

            try
            {

                UserDetails objUser = UserManagement.getUserDetails(userName);

                if (objUser == null)
                {
                    ShowAlert("User does not have right to use application");
                    return;
                }

                if (!objUser.IsActive)
                {
                    ShowAlert("This user is currently deactivated. Please contact system administrator");
                    return;
                }

                if (password.Trim() == objUser.UserPassword)
                {
                    UserManagement.InsertUserLogin(objUser.UserId, loginDate, clientIP, Session.SessionID);

                    objUser.UserHost = clientIP;

                    objUser.UserBrowser = userAgent;

                    Session["UserDetails"] = objUser;

                    FormsAuthentication.SetAuthCookie(txtUserName.Text, false);

                    if (objUser.PreviligeId == 0)
                        ShowAlert("No rights to login into application");
                    else
                        Response.Redirect("main.aspx", false);
                }

                else
                {
                    ShowAlert("Please enter valid username or password");
                }

            }

            catch (Exception ex)
            {
                ShowAlert("An application error occured during user login.");
            }

        }

        public void ShowAlert(string alertMsg)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "alert('" + alertMsg.Replace(",", "") + "');", true);
        }
    }
}

Web.Config


<authentication mode="Forms">
<forms name="_browserData" loginUrl="login.aspx" timeout="30">
</forms>
</authentication>

<authorization>
<deny users="?" />
</authorization>

Hope you like this post. You can find some more posts of your interest on ASP.NET here.

What do you think?

Dear Readers,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Crunching!

Was this article worth reading? Share it with fellow developers too.

DotNetCrunch

DotNetCrunch is a popular blog for latest Microsoft® technologies which is aimed for beginners and intermediate level professionals.