Click here to Skip to main content
Click here to Skip to main content

User Login For WinForm Applications

By , 2 Oct 2008
 
LogonDemo

Introduction

A question was posed in the C# forum today about logging in to an application using the user's Windows account. In essence, if the user is logged into his account, and he tries to run an application, it's kind of pointless (and annoying) to re-request his login info. However, making a user login to an application does allow the programmer to dictate the terms, specifically, what roles the user has on the computer in question. This article demonstrates not only this aspect of application access, but also allows the program to have its own xml-based database of users.

The Windows Authentication Problem

Since we don't have to worry about the user's name and/or password, this process is reduced to a much easier task - determining if the user is in an acceptable group/role. With the .Net framework, this is easy as pie, involving just three lines of code:

using System.Security.Principal;

public bool UserInSystemRole(WindowsBuiltInRole role)
{
    WindowsIdentity  identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(role);
}

The function above is from the supplied sample application, and is called by passing the desired WindowsBuiltInRole ordinal (like WindowsBuiltInRole.Administrator). You can also check for custom roles such as "MySuperRole". Below is the function from the sample application:

using System.Security.Principal;

public bool UserInCustomRole(string role)
{
    WindowsIdentity  identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(identity);
    return principal.IsInRole(role);
}

Sometimes, .Net really does make things too easy on us. :)

The Application Authentication Problem

When you want something application-specific, this is probably the best way to go. The data file can be stored on any network share (for easy administration), and you can go as far as you want or need regarding security. For this sample application, I chose not to implement any kind of encryption or hashing of passwords because that's not what this article is about (and I pretty much didn't feel like doing it). Here's the function used to authenticate via the application's XML-based user database:

public bool ValidateApplicationUser(string userName, string password)
{
    bool validUser = false;

    // if you want to do encryption, I recommend that you encrypt the password 
    // here so that you don't have to mess with the LINQ query below, but you 
    // can still do a direct comparison.

    try
    {
        // setup the filename
        string fileName = System.IO.Path.Combine(Application.StartupPath, "users.xml");

        // load the file
        XDocument users = XDocument.Load(fileName);

        // query the file with LINQ - this query only returns one record from 
        // the file, and only if the user name and password match.
        XElement userElement = (from subitem in 
                    (from item in users.Descendants("user") select item) 
                     where subitem.Element("name").Value.ToLower() == userName.ToLower() 
                     && subitem.Element("password").Value == password 
                     select subitem).SingleOrDefault();

        // if you get here without an exception, and if the returned XElement isn't null
        // then the user is valid
        validUser = (userElement != null);
    }

    catch (Exception ex)
    {
        if (ex != null) {}
    }

    return validUser;
}

Notice that we used our new friend, LINQ, again. LINQ is just too handy to ignore. While I wouldn't use it all the time, it's great for dealing with XML files like our user database.

Notes 

You can easily combine the application-specific authentication with the role validation to further control access to your applications. 

The provided sample application has NOT been thoroughly tested (I simply don't have the time right now), so run your login code through the debugger a couple of times to make sure it's going to do what you want it to do.

History

10/03/2008: Changed the LINQ statement that retrieves the userElement in the ValidateApplicationUser() method to return null instead of waiting for an exception in the event that the user isn't found. I did not change the code in the download file, so remember to make the same change in your own code.

10/02/2008: Original article posted.

  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

John Simmons / outlaw programmer
Software Developer (Senior)
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.
 
My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5 PinmemberYoda018-Aug-12 0:19 
Thanks!
QuestionCongradulations PinmemberMember 362447927-Feb-12 7:27 
It's spelled 'Congratulations'.
QuestionHow to do this against a database? Pinmemberernieball_261-Feb-12 10:11 
Sir, I have posted my problem regarding logins in winforms application. Here is the link:
How to handle user log-in using C# or VB.Net WinForms wherein credentials are from the database?[^]
Do you think your sample could have solve my problem? If it ain't no trouble for you, kindly give me a simple project with a database included. I would highly appreciate your big help and your urgent response! Thank you.
AnswerRe: How to do this against a database? PinmvpJohn Simmons / outlaw programmer1-Feb-12 11:25 
GeneralRe: How to do this against a database? Pinmemberchenandczh21-Feb-12 15:29 
Questionconfused by too many negatives PinmemberMember 243456418-Aug-11 4:30 
Hi,
I'm not sure if I'm missing something here but I can't get my head around the logic used in the buttonOK_Click handler - it may be too many negatives but I'm not sure.
 
Consider the default case where the form has the "Use Windows Authentication" and "Don't Care" options selected.
 
When I click OK it correctly deduces that radioMustBeAdmin is not checked and bypasses the UserInsystemRole(Admin) test. However it then checks whether the radioCanBeAdmin option is not checked (it isn't so the test succeeds) and then tests whether I am not an administrator and, since I am an administrator, the authentication fails !!!
 
Similarly if I select the "Must be Admin" option it verifies that I am an admin and then, because the radioCanBeAdmin checkbox is not checked, it fails me because I am not not-a member of the admin group.
 
or am I missing something?
 
TTFN
ST
Questionif (ex != null) { } PinmemberAlexander M. Batishchev26-Jun-11 6:37 
ex can't be null in a catch-block
AnswerRe: if (ex != null) { } PinmvpJohn Simmons / outlaw programmer27-Jun-11 11:43 
I do that to avoid the compiler warning... Smile | :)
".45 ACP - because shooting twice is just silly" - JSOP, 2010
-----
You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

GeneralRe: if (ex != null) { } PinmemberAlexander M. Batishchev27-Jun-11 20:15 
GeneralMy vote of 5 PinmemberSAKryukov15-May-11 12:14 
This can serve as a good answer to many questions on the topic.
GeneralMy vote of 4 Pinmemberddboarm25-Dec-10 22:18 
great insight to beginning usage and implementation
GeneralGood aarticle PinmemberDonsw22-Jan-09 11:20 
Good article, Nice use of linq. this is as you pointed out a great use of linq.
GeneralVery nice article John PinmvpSacha Barber13-Oct-08 7:52 
I like this one a lot. 5 *
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Very nice article John PinmvpJohn Simmons / outlaw programmer13-Oct-08 8:00 
GeneralRe: Very nice article John PinmvpSacha Barber13-Oct-08 8:02 
GeneralChange To Article PinmvpJohn Simmons / outlaw programmer2-Oct-08 23:26 
I change the text in the article to reflect a better method for retrieving a single record without necessarily throwing an exception. I DID NOT CHANGE THE CODE IN THE DOWNLOAD FILE. The change wasn't necessary, and doesn't make the code any more reliable, but it avoids forcing the sample program to throw an exception if the user isn't found (and avoiding exceptions is always a noble goal).
 
Many thanks to Navaneeth for telling me about it.
 

"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
-----
"...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001
modified on Friday, October 3, 2008 6:16 AM

GeneralSome suggestions PinmemberN a v a n e e t h2-Oct-08 17:32 
John Simmons / outlaw programmer wrote:
A question was posed in the C# forum today

 
typo?
 
Your article is good. But using try/catch for setting validUser flag seems to be a bad idea. You can change the LINQ a bit so that it returns NULL when item is not found. I think code would be much better then.
XElement userElement = (from subitem in 
         		(from item in users.Descendants("user") select item) 
			 where subitem.Element("name").Value.ToLower() == userName.ToLower() 
			 && subitem.Element("password").Value == password select subitem).First();
Change to
XElement userElement = (from subitem in 
         		(from item in users.Descendants("user") select item) 
			 where subitem.Element("name").Value.ToLower() == userName.ToLower() 
			 && subitem.Element("password").Value == 
                                      password select subitem).SingleOrDefault();
return userElement != null;
SingleOrDefault will return NULL instead of throwing exception if item not found.
 

GeneralRe: Some suggestions [modified] PinmvpJohn Simmons / outlaw programmer2-Oct-08 23:10 
GeneralRe: Some suggestions PinmemberN a v a n e e t h5-Oct-08 17:23 
GeneralYour work Pinmembernelsonpaixao2-Oct-08 13:37 
Hi,
 
i am going to check it out your work, i manage login/logout in winforms with database.Rose | [Rose]
 
nelsonpaixao@yahoo.com.br
 
trying to help & get help

GeneralUseful PinmemberDaveyM692-Oct-08 12:36 
I knew this stuff was in there but never got around to investigating. I'm gonna need some of this soon in one of my current projects so bookmarked (to save me the effort of 'googling' and the pain of MSDN) and 5'd! Big Grin | :-D
 
Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)

GeneralNice, but some suggestions... Pinmembermarco_br2-Oct-08 10:50 
Good article: I just have two small suggestions...
 
First: I'd write the catch block like this:
	catch (Exception ex)
	{
		if (ex != null) {}
	}
 
Second: I know with LINQ this is just as easy to manage as XML, but you could at least mention the case where the user base of the application is stored in a Database.
GeneralNice, but some suggestions... (correction) Pinmembermarco_br2-Oct-08 10:53 
GeneralRe: Nice, but some suggestions... (correction) PinmvpJohn Simmons / outlaw programmer2-Oct-08 11:04 
AnswerRe: Nice, but some suggestions... (correction) Pinmembermarco_br3-Oct-08 1:43 
GeneralNice use of Linq in there. PinmvpPete O'Hanlon2-Oct-08 10:23 
Don't tell me you've moved over to the dark side of .NET 3.5 John. Anyway - gets my 5 to counteract the univoting asswipe.
 
Deja View - the feeling that you've seen this post before.
 

My blog | My articles | MoXAML PowerToys



GeneralRe: Nice use of Linq in there. PinmvpJohn Simmons / outlaw programmer2-Oct-08 10:46 
GeneralRe: Nice use of Linq in there. PinmemberJean-Paul Mikkers2-Oct-08 10:59 
GeneralRe: Nice use of Linq in there. Pinmemberjpsstavares3-Oct-08 0:05 
GeneralRe: Nice use of Linq in there. PinmvpPete O'Hanlon2-Oct-08 11:02 
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 2 Oct 2008
Article Copyright 2008 by John Simmons / outlaw programmer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid