Create Login Form with Authentication

Bubbly
Posted by Bubbly under C# category on | Views : 4030
This code demonstrates creating a login dialog box to authenticate users and restrict access to features in an application. The user must first log in, within 3 attempts,either using custom authentication or Windows
Authentication. After the user logs in, the role membership is checked to see if the user is a "Manager" or a Windows Administrator.


Feature Highlights:

A Windows Principal object is used to determine if the user logged into Windows is an Administrator.
A Generic Principal object is used to determine if a user is a member of the "Manager" role.
An XML file is loaded into a DataSet and searched for an appropriate match

Users.cs Class

using System.Security.Principal;
using System.Threading;
using System.IO;
using System;
using System.Data;
using System.Windows.Forms;

public class Users
{

public bool IsLogin(string strName, string strPassword)
{
// Procedure checks that the login exists in the XML file

DataSet dsUsers = new DataSet();
DataRow[] drRows;
bool ret = false;

try {

// Read the XML into a Dataset and filter on name and password for a collection of DataRows.

dsUsers.ReadXml(@"..\..\Users.xml");

drRows = dsUsers.Tables[0].Select("name = '" +
strName + "' and password = '" + strPassword + "'");

// Code must be implemented when adding users to the list to insure
// that there are no 2 users with the same name
// if there is a row in the collection then a record was found

if (drRows.Length > 0)
{ ret = true; }
else
{ ret = false; }

} catch(FileNotFoundException e)
{
MessageBox.Show("Users.Xml file not found.", "Unable to Authenticate user.", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}
return ret;
}

public GenericPrincipal GetLogin(string strName, string strPassword)
{
// Procedure returns a Generic Principal representing the login account

DataSet dsUsers = new DataSet();
DataRow[] drRows = null;

try {

// Read the XML into a Dataset and filter for a collection of DataRows

dsUsers.ReadXml(@"..\..\Users.xml");

drRows = dsUsers.Tables[0].Select("name = '" +
strName + "' and password = '" + strPassword + "'");

} catch( FileNotFoundException e)
{
MessageBox.Show("Users.Xml file not found.","Shutting Down...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
Application.Exit();
}

// Create the Generic Identity representing the User

GenericIdentity GenIdentity = new GenericIdentity(strName);

// Define the role membership an array

string[] Roles = {Convert.ToString(drRows[0]["Role"]), ""};
GenericPrincipal GenPrincipal = new GenericPrincipal(GenIdentity, Roles);
return GenPrincipal;
}

public bool IsAdministrator()
{
// Procedure checks if the Windows Login is an Administrator
// For single role-based validation
// WinPrincipal new WindowsPrincipal(WindowsIdentity.GetCurrent())
// For repeated role-based validation

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

WindowsPrincipal WinPrincipal = (WindowsPrincipal) Thread.CurrentPrincipal;

// Check if the user account is an Administrator

if (WinPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
else
{
return false;
}
}
}



On login Form Submit Button click event
using System.Security.Principal;

private void btnOK_Click(object sender, System.EventArgs e)
{
// Instantiate a custom Users class

Users objUser = new Users();
GenericPrincipal GenPrincipal;
string strName = txtUserName.Text;
string strPassword = txtPassword.Text;

// Check for Windows Administrator. Administrator can bypass
// custom security system.

if (chkAdministratorAccount.Checked)
{
if (objUser.IsAdministrator())
{
// Display the Users Name (Windows or Generic)

MessageBox.Show(Thread.CurrentPrincipal.Identity.Name +
" has logged in successfully!","Login Successful",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Increment login attempts

intLoginAttempts += 1;

MessageBox.Show("User not an Administrator. Please provide a User Name and Password.", this.Text,
MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
}
}
else
{
// Check that the login exists

if (objUser.IsLogin(strName, strPassword))
{
GenPrincipal = objUser.GetLogin(strName, strPassword);
Thread.CurrentPrincipal = GenPrincipal;

// Display the Users Name (Windows or Generic)

MessageBox.Show(Thread.CurrentPrincipal.Identity.Name +
" has logged in successfully!", "Login Successful",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else
{
// Increment login attempts
intLoginAttempts += 1;
// After the 3 attempts quit the application
if (intLoginAttempts >= 3)
{
MessageBox.Show("Too many failed login attempts",this.Text,
MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
Application.Exit();
}
else
{
MessageBox.Show("User Name not found. Please try again", this.Text,MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}


XML file
<?xml version="1.0" encoding="utf-8" ?> 
<users>
<user>
<name>Deepika</name>
<password>pass</password>
<role>Manager</role>
</user>
<user>
<name>Ratna</name>
<password>pass</password>
<role>Sales</role>
</user>
</users>

Comments or Responses

Login to post response