Windows Authentication in winform Application

Today one of my friend asked me how we can perform validating user windows login credentials. In past also i saw in many forums people asking similar questions.

actaully there are 2 different scenarios

  1. Get the currently logged in windows user name.

  2. Prompt the user for user and password, and validate the provided user name and password are a valid user credentials

following is the c# code which will answer these scenarios.

1)  Get currently logged in user details: This is pretty straight forward approach. We can achieve this by using the WindowsIdentity class of System.Security.Principal namespace. This class provides a static method, getCurrent(), which return a object of WindowsIdentity.

Bellow is the code you can use to get the current logged in user details.

 public string GetloggedinUserName()
{
 
System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
return currentUser.Name;
}
  1. Validate windows credentials provided by user: This is little complex compared to above as we need to call a windows API using IntropServices. To accomplish this we need to add a extern function declaration, and then call the function. Following code will help you to understand this better.
class Program
    {
                     
        [System.Runtime.InteropServices.DllImport("advapi32.dll")]
        public static extern bool LogonUser(string userName, string domainName, string password, int LogonType, int LogonProvider,ref IntPtr phToken);
 
        static void Main(string[] args)
        {
            Program obj = new Program();
            bool isValid = obj.IsValidateCredentials("myUserName","MyPassword","MyDomain");
            Console.WriteLine(isValid == true ? "Valid User details" : "Invalid User Details");
            Console.Read();
        }
               
        public bool IsValidateCredentials(string userName, string password, string domain)
        {
            IntPtr tokenHandler = IntPtr.Zero;
            bool isValid = LogonUser(userName, domain, password, 2, 0, ref tokenHandler);
            return isValid;
        }
    }

 Hope this will be useful for people who want to perform windows authentication in winform applications...

Happy coding  regular smileregular smileregular smile

This article is part of the GWB Archives. Original Author: Ramaraju

New on Geeks with Blogs