Monday, 9 June 2014

ASP.Net Custom Authentication Forms Based Security

ASP.Net Custom Authentication Forms Based Security



In this article we will learn how to implement Forms-Based Authentication in ASP.Net website. Forms authentication uses an authentication ticket that is created when a user logs on to a site, and then it tracks the user throughout the site. 


implementation, code,ASP.NET Security,custom authentication  simple,authorization  sample,.NET security  forms authentication, tutorial,Forms Authentication,Custom Authentication

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. Find the source code below: -

There are following aspects to implement 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:

- Windows Authentication
- Forms Authentication
- Passport Authentication
- 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.

Code - ASP.NET Authentication and Authorization


Login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ASP.Net Custom Authentication Forms Based Security</title>
    <link href="css/structure.css" rel="stylesheet" />
    <script type="text/javascript">
        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;
            }
        }
    </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>

Login.aspx.cs
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 exp)
        {
            ShowAlert("An application error occured during user login.");
        }
    }

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

    }

Web.Config
<authentication mode="Forms">
      <forms name="_browserData" loginUrl="login.aspx" timeout="30">
        <!--<credentials passwordFormat="Clear">
        </credentials>-->
      </forms>
    </authentication>
    <authorization>
      <deny users="?" />

    </authorization>

No comments:

Post a Comment

SQL SERVER – Disk Space Monitoring – Detecting Low Disk Space on Server

CREATE PROCEDURE [CSMSDVLP].[DiskSpaceMonitor] @mailProfile nvarchar(500), @mailto nvarchar(4000), @threshold INT, @logfile nvarchar(40...