Form based Authentication from a database table in .NET

Webconfig

   <authentication mode="Forms">
       
        <forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx" timeout="2">
          <credentials passwordFormat="Clear">
            <user name="UserName1" password="UserName1"/>
            <user name="UserName2" password="UserName2"/>
          </credentials>
          </forms>
       
      </authentication>
 

The User credentials are stored in the Webconfig ,which is ofcourse a bad practice


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

deny User = ? no user can access the application as anonymous

Login.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;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

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

        }

        protected void InputButton_Click(object sender, EventArgs e)
        {
            if (AuthenticateUser(NameInput.Text, PasswordInput.Text))
            {
                FormsAuthentication.RedirectFromLoginPage(NameInput.Text, chk.Checked);

            }
            else
            {
                OutputMessage.Text="Invalid User Name or password";
            }


        }

        private bool AuthenticateUser(string username, string password)
        {
            string cs = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;

            using (SqlConnection conn = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spAuthenticateUser", conn);
                cmd.CommandType=CommandType.StoredProcedure;

                string encrypt = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
                SqlParameter username1 = new SqlParameter("@Username", username);
                SqlParameter password1 = new SqlParameter("@Password", encrypt);

                cmd.Parameters.Add(username1);
                cmd.Parameters.Add(password1);

                conn.Open();
                int ret = (int)cmd.ExecuteScalar();
                return ret == 1;

            }
        }

    }
}

LOGIN.html

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="WebApplication1.Login" %>
<!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>
                <asp:Label id="StaticMsg" runat="server" Text="LOGIN"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                <asp:Label id="Name" runat="server" Text="User Name "></asp:Label>
                </td>
                <td>
                <asp:TextBox id="NameInput" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label id="Pswd" runat="server" Text="Password"></asp:Label>
                </td>
                <td>
                    <asp:TextBox id="PasswordInput" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:CheckBox id="chk" runat="server" />
                     <asp:Label id="Remember" runat="server" Text="Remember Me"></asp:Label>
                </td>
                <td>
                   
                    <asp:Button ID="InputButton" runat="server" OnClick="InputButton_Click" Text="Login"/>
                </td>
            </tr>
            <tr>
                <td>
                <asp:Label ID="OutputMessage" runat="server"></asp:Label>
                </td>
             
            </tr>

        </table>
        <asp:HyperLink ID="hypLink" runat="server" Text="Click here to register!!!"  NavigateUrl="~/Registration/Registration.aspx"></asp:HyperLink>

    </div>
    </form>
</body>
</html>

WebConfig for Registration page

<connectionStrings>
    <add name="DBConn" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Apotheosis\Documents\Visual Studio 2012\Projects\1-clickPublish\1-clickPublish\App_Data\1-ClickPublish.mdf';Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Registration .axpz

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string cs = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("userRegister", conn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    string encrypt = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "SHA1");
                    SqlParameter userName= new SqlParameter("@UserName",TextBox1.Text);
                    SqlParameter password= new SqlParameter("@Password",encrypt);
                    SqlParameter email=    new SqlParameter("@email",TextBox3.Text);

                    cmd.Parameters.Add(userName);
                    cmd.Parameters.Add(password);
                    cmd.Parameters.Add(email);

                    conn.Open();

                    int retruncode=(int)cmd.ExecuteScalar();

                    if(retruncode == -1)
                    {
                        outputMessage.Text="User Already Exists ";
                    }
                    else
                    {
                        Response.Redirect("~/Login.aspx");
                    }
                }
            }
        }
    }
}

Registration.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Registration.aspx.cs" Inherits="WebApplication1.Registration.Registration" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table style="border:1px solid red;">
         <tr>
             <asp:Label ID="UsrRegistration" runat="server" Text="UserRegistration"></asp:Label>
         </tr>
         <tr>
             <td>
             <asp:Label ID="UserName" runat="server" Text="User Name"></asp:Label>
             </td>
             <td>
             <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
             </td>

         </tr>
         <tr>
             <td>
             <asp:Label ID="Password" runat="server" Text="Password "></asp:Label>
             </td>
             <td>
             <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
             </td>
         </tr>
         <tr>
             <td>
             <asp:Label ID="Email" runat="server" Text="Email"></asp:Label>
             </td>
             <td>
             <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
             </td>
         
         </tr>
         <tr>
             <td>
             <asp:Button ID="Button1" runat="server" Text="Submit"  OnClick="Button1_Click"/>
             </td>
         </tr>
         <tr>
             <td>
                 <asp:Label ID="outputMessage" runat="server" ></asp:Label>
             </td>
         </tr>

     </table>
    </div>
    </form>
</body>
</html>




Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6