Get Windows credentials from C# application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;

namespace ConsoleApplication1
{
    class Program
    {
        static string loggedInUser;
        static string userLocalGroup = null;
        static string usersGroupSIDs = null;
        static string currentUserDetails;

        static void Main(string[] args)
        {

            loggedInUser = WindowsIdentity.GetCurrent().Name;
            WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());


            IdentityReferenceCollection irc = WindowsIdentity.GetCurrent().Groups;
            foreach (IdentityReference ir in irc)
            {
                usersGroupSIDs = usersGroupSIDs + " , " + ir.Value.ToString();
            }
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                userLocalGroup = userLocalGroup + " Adminstrator ,";
            if (principal.IsInRole(WindowsBuiltInRole.AccountOperator))
                userLocalGroup = userLocalGroup + " AccountOperator ,";
            if (principal.IsInRole(WindowsBuiltInRole.BackupOperator))
                userLocalGroup = userLocalGroup + " BackupOperator ,";
            if (principal.IsInRole(WindowsBuiltInRole.Guest))
                userLocalGroup = userLocalGroup + " Guest ,";
            if (principal.IsInRole(WindowsBuiltInRole.PowerUser))
                userLocalGroup = userLocalGroup + " PowerUser";
            if (principal.IsInRole(WindowsBuiltInRole.PrintOperator))
                userLocalGroup = userLocalGroup + "PrintOperator ,";
            if (principal.IsInRole(WindowsBuiltInRole.Replicator))
                userLocalGroup = userLocalGroup + " Replicator ,";
            if (principal.IsInRole(WindowsBuiltInRole.SystemOperator))
                userLocalGroup = userLocalGroup + " SystemOperator ,";
            if (principal.IsInRole(WindowsBuiltInRole.User))
                userLocalGroup = userLocalGroup + " User";

            // }
            currentUserDetails = WindowsIdentity.GetCurrent().ToString();

            Console.WriteLine("Logged in user : " + loggedInUser);
            Console.WriteLine("Logged in user belongs to Local Groups : " + userLocalGroup);

            Console.WriteLine("Logged in user belongs to SID Groups : " + usersGroupSIDs);
            Console.WriteLine("Current user Object is  : " + currentUserDetails);
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s