C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » Application windows, menus & toolbars »

Create "Login Form" with authentication


Posted Date: 15 May 2009    Resource Type: Code Snippets    Category: Application windows, menus & toolbars
Author: Deepika HaridasMember Level: Diamond    
Rating: 1 out of 5Points: 20



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);
}
}
}
}


I am attaching design view of the Form to get an Idea..
And also attaching XML file (name it as Users.xml while using)

Attachments



  • Create "Login Form" in Windows Application (28460-1541-Users.txt)


  • Responses

    Author: greeny_1984    16 May 2009Member Level: Diamond   Points : 0
    Hi,

    Nice post deepika..

    usefull for many people

    regards,

    greeny


    Author: Shuby Arora    24 May 2009Member Level: Gold   Points : 0
    Deepika its a good work


    Author: Pandurang Chavan    09 Jun 2009Member Level: Silver   Points : 0
    Hi

    you have done great work for forum..

    Regards ...
    pandurang


    Author: Ravi kiran    21 Sep 2009Member Level: Bronze   Points : 1
    Hi deepika,

    I am a new bee to desktop application, but had 3 yrs exp in webapplication. how can i avoid accesing any form without login like in web applications authentication. I don't know such an concept exists in desktop application or not. Could plz help me in this regard?


    Feedbacks      
    Popular Tags   What are tags ?   Search Tags  
    Sign In to add tags.
    Xml  .  Windows  .  Permissions  .  Messagebox  .  Login  .  Form  .  

    Post Feedback


    This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
    You must Sign In to post a response.
    Next Resource: Dialog box creation using java.
    Previous Resource: Create your own Detail View in Windows Application
    Return to Discussion Resource Index
    Post New Resource
    Category: Application windows, menus & toolbars


    Post resources and earn money!
     
    More Resources



    dotNet Slackers

    About Us    Contact Us    Privacy Policy    Terms Of Use