How to get Security UserId after windows Starts a Session

So what happens when user is logged into the system? When you type your password correctly and you authorize yourself as authorized user then system starts your session and creates user's token together with its security ID (SID). This SID is located in domain controller (when user is a member of domain) or in a local SAM database (when accessing local computer).

SIDs are very important giving uniqueness in Windows environment; they are variable-length and they are composed from many parts.

 

Following method is very important when working with international environments. Operating systems can be localized into different languages with different general names for objects and that is why SIDs are the best way how to identify those objects independently from current language version. Those samples present how SID and object names can be found.

 

using System; 

using System.Drawing; 

using System.Collections; 

using System.ComponentModel; 

using System.Windows.Forms; 

using System.Data; 

// For Application 

using System.Runtime.InteropServices; 

using System.Text; 

using System.Security.Principal; 

namespace SecurityId 

{ 

          /// <summary> 

          /// Summary description for Form1. 

          /// </summary> 

          public class Form1 : System.Windows.Forms.Form 

          { 

                   /// <summary> 

                   /// Required designer variable. 

                   /// </summary> 

                   private System.ComponentModel.Container components = null; 

                   public Form1() 

                   { 

                             // 

                             // Required for Windows Form Designer support 

                             // 

                             InitializeComponent(); 

                             // 

                             // TODO: Add any constructor code after InitializeComponent call 

                             // 

                   } 

                   /// <summary> 

                   /// Clean up any resources being used. 

                   /// </summary> 

                   protected override void Dispose( bool disposing ) 

                   { 

                             if( disposing ) 

                             { 

                                      if (components != null 

                                      { 

                                                components.Dispose(); 

                                      } 

                             } 

                             base.Dispose( disposing ); 

                   } 

                   #region Windows Form Designer generated code 

                   /// <summary> 

                   /// Required method for Designer support - do not modify 

                   /// the contents of this method with the code editor. 

                   /// </summary> 

                   private void InitializeComponent() 

                   { 

                             this.listBox1 = new System.Windows.Forms.ListBox(); 

                             this.SuspendLayout(); 

                             //  

                             // listBox1 

                             //  

                             this.listBox1.Location = new System.Drawing.Point(0, 8); 

                             this.listBox1.Name = "listBox1"; 

                             this.listBox1.Size = new System.Drawing.Size(496, 95); 

                             this.listBox1.TabIndex = 0; 

                             //  

                             // Form1 

                             //  

                             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); 

                             this.ClientSize = new System.Drawing.Size(496, 166); 

                             this.Controls.Add(this.listBox1); 

                             this.Name = "Form1"; 

                             this.Text = "Form1"; 

                             this.Load += new System.EventHandler(this.Form1_Load); 

                             this.ResumeLayout(false); 

                   } 

                   #endregion 

                   /// <summary> 

                   /// The main entry point for the application. 

                   /// </summary> 

                   [STAThread] 

                   static void Main()  

                   { 

                             Application.Run(new Form1()); 

                   } 

                   //ApplicationDecleration 

                   #region 

                   const int NO_ERROR = 0; 

                   private System.Windows.Forms.ListBox listBox1; 

                   const int ERROR_INSUFFICIENT_BUFFER = 122; 

                   enum SID_NAME_USE  

                   { 

                             SidTypeUser = 1, 

                             SidTypeGroup, 

                             SidTypeDomain, 

                             SidTypeAlias, 

                             SidTypeWellKnownGroup, 

                             SidTypeDeletedAccount, 

                             SidTypeInvalid, 

                             SidTypeUnknown, 

                             SidTypeComputer 

                   } 

                   [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError = true)] 

                   static extern bool LookupAccountName ( 

                             string lpSystemName, 

                             string lpAccountName, 

                             [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, 

                             ref uint cbSid, 

                             StringBuilder ReferencedDomainName, 

                             ref uint cchReferencedDomainName, 

                             out SID_NAME_USE peUse);  

                   [DllImport("advapi32", CharSet=CharSet.Auto, SetLastError=true)] 

                   static extern bool ConvertSidToStringSid( 

                             [MarshalAs(UnmanagedType.LPArray)] byte [] pSID,  

                             out IntPtr ptrSid); 

                   [DllImport("kernel32.dll")] 

                   static extern IntPtr LocalFree(IntPtr hMem); 

                   #endregion 

                   private void Form1_Load(object sender, System.EventArgs e) 

                   { 

                             // get current user's identity 

                             WindowsIdentity wi = WindowsIdentity.GetCurrent(); 

                             string accountName = wi.Name.ToString(); 

                             byte [] Sid = null; 

                             uint cbSid = 0; 

                             StringBuilder referencedDomainName = new StringBuilder(); 

                             uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; 

                             SID_NAME_USE sidUse; 

                             int err = NO_ERROR; 

                             // get data for size of buffer in cbSid and cchReferencedDomainName 

                             if (!LookupAccountName(null,accountName,Sid,ref cbSid,referencedDomainName,ref
                             cchReferencedDomainName,
out sidUse)) 

                             { 

                                      err = Marshal.GetLastWin32Error(); 

                                      if (err == ERROR_INSUFFICIENT_BUFFER) 

                                      { 

                                                Sid = new byte[cbSid]; 

                                                referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); 

                                                err = NO_ERROR; 

                                                // !!! - FIND SID FOR USER !!! 

                                                if (!LookupAccountName(null,accountName,Sid,ref
                                                cbSid,referencedDomainName,
ref cchReferencedDomainName,out sidUse)) 

                                                          err = Marshal.GetLastWin32Error(); 

                                      } 

                             } 

                             if (err == 0) 

                             { 

                                      IntPtr ptrSid; 

                                      // convert sid value into well formatted string 

                                      if (!ConvertSidToStringSid(Sid,out ptrSid)) 

                                      { 

                                                err = Marshal.GetLastWin32Error(); 

                                                //MessageBox.Show("Could not convert sid to string. Error : {0}" + err); 

                                      } 

                                      else 

                                      { 

                                                string sidString = Marshal.PtrToStringAuto(ptrSid); 

                                                LocalFree(ptrSid); 

                                                listBox1.Items.Add("Found sid {0} : {1}" + "-" + sidUse + "-" + sidString); 

                                                listBox1.Items.Add(accountName); 

                                                listBox1.Items.Add(referencedDomainName); 

                                      } 

                             } 

                             else 

                                      MessageBox.Show( "Error : {0}"+ err); 

                             //MessageBox.Show(""); 

                   } 

          }

}