Wednesday, 11 April 2018

0221 Maintain Security Form authentication

Maintain Security using Form Authentication
 

Form authentication display an interface to collect  user information. It is actually a login form  to collect user name and password . Form authentication is advantageous , the kind of application, where exists large number of  growing user and application is beyond the boundary of a network or a group of user . Most of the commercial web application, uses Form authentication for authentication purpose.

How to do Form Authentication :

  • You need to set web.config file.
  • Create a login form , to collect user information
  • Create a database, hold the record of valid user and password.
  • Write code to send user information from login page to the database
  • Write code to send database response to the login page
here is the web config file  setting with Forms authentication

xml version="1.0"?>
     <configuration>
                    <system.web>
                        <authentication mode="Forms">
                             <forms loginUrl="Login.aspx" />
                       </authentication>
                  </system.web>
</configuration>


here is the web config file  setting with Forms authentication
and user credential
 
xml version="1.0"?>
<configuration >
<system.web>
        <authentication mode="Forms">
                      <forms name="Sampel" loginUrl="~Login.aspx">
                      <credentials passwordFormat="MD5">
                              <user name="user1" password="D72A0F2C-6865-4186-846E-A9CCF0DC894D"/>
                              <user name="user2" password="3ED33882-59CE-4116-84AE-FD468CEC279C"/>
                              <user name="user3" password="61BC4B71-AB7E-423C-901C-90ADEC6109AF"/>
                      </credentials>
                     </forms>
             </authentication>
</system.web>
</configuration>
 







The first setting you need to do , to set authentication mode to forms. You need to write the forms login user name and respective credentials in the credentials section.How to discard other to logging the application, "deny" keyword is used as follows.



xml version="1.0"?>
<configuration >
<system.web>
           <authentication mode="Forms">
                    <forms name="Sampel" loginUrl="~Login.aspx">
                                  <credentials passwordFormat="MD5">
                                         <user name="user1" password="D72A0F2C-6865-4186-846E-A9CCF0DC894D"/>
                                         <user name="user2" password="3ED33882-59CE-4116-84AE-FD468CEC279C"/>
                                         <user name="user3" password="61BC4B71-AB7E-423C-901C-90ADEC6109AF"/>
                                   </credentials>
                    </forms>
            </authentication>
        <deny users="*" />
</system.web>
</configuration>
 
Here are the settings of web.config
  • Authentication 
  1. mode : Authentication mode is set to forms authentication.
  • Forms 
  1. name : The name of the cookie who had the forms name is save. When user is enter, with he is credential, value save in cookie.
  2. loginUrl: The relative URL of the login page.
  3. path: The part where the cookie will be save.
  4. timeout:It is the time limit, how long the cookie will be persist in user machines. By default is 30 minutes.
  • Credential :
  1. password format :Password is encrypted with this techniques like MD5,SHA1 etc.
  • User :
    1. name : the login name of the user. 
    2. Password : password of user.
Here is the use of the setting 
 
<system.web>
           <authentication mode="Forms">
                       <forms loginUrl="~Login.aspx"
                                  protection="All"
                                  timeout="30"
                                  name=".ASPXAUTH"
                                  path="/"
                                  requireSSL="false"
                                  slidingExpiration="true"  >

                          </forms>
           </authentication>
</system.web>


Creating a login form

aspx Code

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
       </head>
              <body>
                           <form id="form1" runat="server">
                           <div>
                           <div style="border:1px solid black;width:300px;">
                           <table >
                            <tr>
                             <td>User Name :
                             </td>
                             <td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                             </td>
                             </tr>
                             <tr>
                            <td>Password :
                           </td>
                           <td><asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
                           </td>
                           </tr>
                          <tr>
                        <td>
                        </td>
                               <td><asp:Button ID="id_Login" runat="server" Text="Login"
onclick="id_Login_Click" />
                        </td>
                         </tr>
                         </table>
                         </div>
                         </div>
                        </form>
               </body>
        </html>

C# Code 

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

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

            }
            protected void id_Login_Click(object sender, EventArgs e)
           {
                    if (FormsAuthentication.Authenticate(this.txtUserName.Text, this.txtPassword.Text))
                      {
                               FormsAuthentication.RedirectFromLoginPage("~/Home.aspx",true);
                      }
                     else
                      {

                       }
        }
}


Here we have created, a login form with username and password to be  enter in the form. When login button is pressed, the program verify that user name and password is not blank. Form authentication class comes under System.Web.Security  namespace. Forms authentication check the user credential with the web.config file. Forms authentication class , if found valid input , redirect  the application to the homepage, else if found invalid, redirect the application to the login page again. 


Login Form










In this kind of application there is an option of sign out. Forms authentication class provide the sign out option when user try to sign out.

protected void btnSignOut_Click(object sender, EventArgs e)
{
           FormsAuthentication.SignOut();
}






Database user authentication
 

Storing user information to web.config file is not always helpful. It is not possible to change web.config file each time, a user change his password or a new user is added. Most of the software uses database authentication to authenticate data. Database tables store the information of the username and password. When a validation request is come,request data is verified with the data stored in the database. The stored data should be encrypted format. Password is secret key of a user, it should not be disclosed to anyone else, maybe it is system administrator.






                   To handle the situation form authentication class provide method for Password encryption. Thus a password can be encrypted  and store into  a tables. Forms authentication allowed to type of encryption MD5,SH1 format. Below is the example how a password can be encrypted using forms authentication class.




 
string passowrd = FormsAuthentication.HashPasswordForStoringInConfigFile("Password", "SHA1");

Database to add new user
 

Database hold collection of of tables, and table hold rows and columns. You can add dynamically you data to the database. Consider the situation, where user can register in a portal. Each time a new user is generated, user choose his username and password.To handle this, a good application store data of an user to the database as a new record. Below is the example of  inserting new data to the database.


 

protected void id_CreateNewUser_Click(object sender, EventArgs e)
{
                  string conString = @" Your Connection String";
                  string cmdString="Insert into tbl_user(user_name,passowrd)  values('"+this.txtUserName.Text.ToString()+"','"+this.txtPassword.Text.ToString()+"')";

                SqlConnection con = new SqlConnection(conString);

                 con.Open();

                SqlCommand cmd = new SqlCommand(cmdString, con);

               try
              {

                object i = cmd.ExecuteScalar();

              }
             catch 
        { 
        }
            finally 
       { 
        con.Close(); 
       }
}

Authentication from database 

A user try to loging the application with his credentials, the application send the data to database. Database verify it with the record stored in it. If found a valid record, database send indicator, if found invalid record, database send another indicator. Depending upon on the indicator, the application redirect to the homepage or  prevent user from login. Below is a example of database validation.

protected void id_ValidateUser_Click(object sender, EventArgs e)
{
         int id = 0;
         string conString = @"Your Connection String";

         string passowrd =   FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtPassword.Text.ToString(), "SHA1");

          string cmdString = "Select id from tbl_user where user_name='"+this.txtUserName.Text.ToString() +"' and passowrd='" + passowrd+"'";

          SqlConnection con = new SqlConnection(conString);

          con.Open();

          SqlCommand cmd = new SqlCommand(cmdString, con);

          try
           {
            SqlDataReader reader=cmd.ExecuteReader();

           while (reader.Read())
          {
                  id=Convert.ToInt16(reader[0]);
           }
       }
catch 
         { }
finally
{
       con.Close();
}

       if (id > 0)
          {
            //valid user
          }
           else
          {
             //invalid user
          }

}






No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...