Monday, August 12, 2019

Form based login authentication using user list in web.config file

In this article i have explain how to login authentication using web.config file in asp.net c#.

for doing this add the following code in web.config file

<system.web>
    <compilation debug="true" targetFramework="4.6"/>
    <httpRuntime targetFramework="4.6"/>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx">
      <credentials passwordFormat="Clear">
        <user name="brij" password="brijhbti"/>
        <user name="nisha" password="nisha"/>
      </credentials>
    </forms>
  </authentication>
  <authorization>
    <deny users="?"/>
  </authorization>
  </system.web>

Add Login.aspx web form and add the following code.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>User Name:</td>
                    <td><input type="text" id="txtUserName" runat="server" /> </td>
                </tr>
                 <tr>
                    <td>Password:</td>
                    <td><input type="password" id="txtPassword" runat="server" /> </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblError" runat="server"></asp:Label>
                    </td>
                </tr>
                 <tr>
                    <td><asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" /></td>
                    <td><asp:Button ID="btnCancel" runat="server" Text="Cancel" /></td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

add the following c# code into Login.aspx.cs

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

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

        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (FormsAuthentication.Authenticate(txtUserName.Value, txtPassword.Value))
            {
                //true=to create a durable cookie(once that is saved across browser session) otherwise false. 
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,false);
            }
            else
            {
                lblError.Text = "Wrong User name or password !";
            }
        }
    }
}

Featured Post

What is JavaScript? What is the role of JavaScript engine?

  The JavaScript is a Programming language that is used for converting static web pages to interactive and dynamic web pages. A JavaScript e...