Click here to Skip to main content
11,581,186 members (60,331 online)
Click here to Skip to main content

User Login For WinForm Applications

, 2 Oct 2008 CPOL 94.8K 3.3K 131
Rate this:
Please Sign up or sign in to vote.
Discusses windows authentication and application-specific authentication for WinForm applications
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. Smile | :)

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)

Share

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.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sepehr Mohammadi26-Oct-13 7:15
memberSepehr Mohammadi26-Oct-13 7:15 
QuestionHave you implemented Windows Authentication? Pin
nithinkamble23-Sep-13 20:22
membernithinkamble23-Sep-13 20:22 
AnswerRe: Have you implemented Windows Authentication? Pin
John Simmons / outlaw programmer24-Sep-13 0:58
memberJohn Simmons / outlaw programmer24-Sep-13 0:58 
GeneralMy vote of 5 Pin
Yoda018-Aug-12 0:19
memberYoda018-Aug-12 0:19 
QuestionCongradulations Pin
Member 362447927-Feb-12 7:27
memberMember 362447927-Feb-12 7:27 
QuestionHow to do this against a database? Pin
ernieball_261-Feb-12 10:11
memberernieball_261-Feb-12 10:11 
AnswerRe: How to do this against a database? Pin
John Simmons / outlaw programmer1-Feb-12 11:25
mvpJohn Simmons / outlaw programmer1-Feb-12 11:25 
GeneralRe: How to do this against a database? Pin
chenandczh21-Feb-12 15:29
memberchenandczh21-Feb-12 15:29 
Questionconfused by too many negatives Pin
Member 243456418-Aug-11 4:30
memberMember 243456418-Aug-11 4:30 
Questionif (ex != null) { } Pin
Alexander M. Batishchev26-Jun-11 6:37
memberAlexander M. Batishchev26-Jun-11 6:37 
ex can't be null in a catch-block
AnswerRe: if (ex != null) { } Pin
John Simmons / outlaw programmer27-Jun-11 11:43
mvpJohn Simmons / outlaw programmer27-Jun-11 11:43 
GeneralRe: if (ex != null) { } Pin
Alexander M. Batishchev27-Jun-11 20:15
memberAlexander M. Batishchev27-Jun-11 20:15 
GeneralMy vote of 5 Pin
SAKryukov15-May-11 12:14
memberSAKryukov15-May-11 12:14 
GeneralMy vote of 4 Pin
ddboarm25-Dec-10 22:18
memberddboarm25-Dec-10 22:18 
GeneralGood aarticle Pin
Donsw22-Jan-09 11:20
memberDonsw22-Jan-09 11:20 
GeneralVery nice article John Pin
Sacha Barber13-Oct-08 7:52
mvpSacha Barber13-Oct-08 7:52 
GeneralRe: Very nice article John Pin
John Simmons / outlaw programmer13-Oct-08 8:00
mvpJohn Simmons / outlaw programmer13-Oct-08 8:00 
GeneralRe: Very nice article John Pin
Sacha Barber13-Oct-08 8:02
mvpSacha Barber13-Oct-08 8:02 
GeneralChange To Article Pin
John Simmons / outlaw programmer2-Oct-08 23:26
mvpJohn Simmons / outlaw programmer2-Oct-08 23:26 
GeneralSome suggestions Pin
N a v a n e e t h2-Oct-08 17:32
memberN a v a n e e t h2-Oct-08 17:32 
GeneralRe: Some suggestions [modified] Pin
John Simmons / outlaw programmer2-Oct-08 23:10
mvpJohn Simmons / outlaw programmer2-Oct-08 23:10 
GeneralRe: Some suggestions Pin
N a v a n e e t h5-Oct-08 17:23
memberN a v a n e e t h5-Oct-08 17:23 
GeneralYour work Pin
nelsonpaixao2-Oct-08 13:37
membernelsonpaixao2-Oct-08 13:37 
GeneralUseful Pin
DaveyM692-Oct-08 12:36
memberDaveyM692-Oct-08 12:36 
GeneralNice, but some suggestions... Pin
marco_br2-Oct-08 10:50
membermarco_br2-Oct-08 10:50 
GeneralNice, but some suggestions... (correction) Pin
marco_br2-Oct-08 10:53
membermarco_br2-Oct-08 10:53 
GeneralRe: Nice, but some suggestions... (correction) Pin
John Simmons / outlaw programmer2-Oct-08 11:04
mvpJohn Simmons / outlaw programmer2-Oct-08 11:04 
AnswerRe: Nice, but some suggestions... (correction) Pin
marco_br3-Oct-08 1:43
membermarco_br3-Oct-08 1:43 
GeneralNice use of Linq in there. Pin
Pete O'Hanlon2-Oct-08 10:23
mvpPete O'Hanlon2-Oct-08 10:23 
GeneralRe: Nice use of Linq in there. Pin
John Simmons / outlaw programmer2-Oct-08 10:46
mvpJohn Simmons / outlaw programmer2-Oct-08 10:46 
GeneralRe: Nice use of Linq in there. Pin
Jean-Paul Mikkers2-Oct-08 10:59
memberJean-Paul Mikkers2-Oct-08 10:59 
GeneralRe: Nice use of Linq in there. Pin
jpsstavares3-Oct-08 0:05
memberjpsstavares3-Oct-08 0:05 
GeneralRe: Nice use of Linq in there. Pin
Pete O'Hanlon2-Oct-08 11:02
mvpPete O'Hanlon2-Oct-08 11:02 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 2 Oct 2008
Article Copyright 2008 by John Simmons / outlaw programmer
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid