Saturday, September 21, 2013

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

No comments:

Post a Comment

Thank you for your feedback