How to Create Manually Form Authentication website in Asp.Net

Leave a Comment
Create a new website in Visual Studio by going through File - > New Website.

Right Click Solution Explorer and add a new page called login.aspx and copy-paste following code.
<form id="form1" runat="server">
    <div id="login">
        <asp:TextBox ID="txt_username" placeholder="User Name" runat="server"></asp:TextBox>
        <asp:TextBox ID="txt_password" placeholder="Password" runat="server"></asp:TextBox>
        <asp:Button ID="btn_login" runat="server" Text="Login" OnClick="btn_login_Click" />
    </div>
    </form>

Double click the button (ID=”btn_login”) that will create click event of the OnClick=”btn_login_Click”. Now add below code in the code behind file of the login.aspx page(login.aspx.cs).
protected void btn_login_Click(object sender, EventArgs e)
    {
        if (txt_username.Text == "kisan" && txt_password.Text == "password")
        {
            FormsAuthentication.RedirectFromLoginPage(txt_username.Text, true);
        }
    }

You will import two Header in login.aspx.cs page to use authentication.
using System.Web.Security;
using System.Security.Principal;

In above code, I am using FormAuthentication.RedirectFromLoginPage method of FormsAuthentication object and passing username and Remember Me status true.

Create Web.Config file setting
<system.web>
    <authentication mode="Forms">
      <forms defaultUrl="Default.aspx" loginUrl="~/login.aspx" slidingExpiration="true" timeout="40">
      </forms>
    </authentication>
  </system.web>

See AlsoSpecific Page/Folder Authorization in web.config

Let me explain in brief what are different attributes of <forms> tag are.

  • defaultUrl is the name of the page where user will be redirected by default after they are logging in from home page or not secured page.
  • loginUrl is the name of the page where user will be redirected when they will try to enter into secure page/folders of the website.
  • slidingExpiration is the attribute that defines whether you want users session to slide. If they are continuing their work on secure page.
  • Timeout value defines duration (in minutes) of the user session after that user session will expire (If slidingExpiration is false otherwise timeout is count after last hit of user to the website).)

Download Complete Source Code

0 comments:

Post a Comment