Alex Rivera | Logout

How to get a Unique ID for the current user's logon session in windows - c#

Asked 2011-05-19T15:33:11.483
9

I need to get a value that uniquely identifies the current windows user's logon session. This is for a winforms app, not ASP.NET. I'll be retrieving this from within multiple processes so it needs to return the same value when retrieved within the same logon session. It only needs to be unique on the current machine for the duration of all user sessions - e.g. until the machine is next restarted.

I think the Windows Logon Id is the right thing, but seems a bit of a pain to retrieve. Is there anything else or any easier way to get this?

I'll be using the ID to include in an address of a named pipes service to communicate between two processes running on the machine. I want to include the Logon Id to avoid conflicts when there are multiple users logged in, including perhaps multiple sessions of the same user.

Edit
Report

1 Answer

21

The easiest way to get Session Id is to look at Process.SessionId property:

System.Diagnostics.Process.GetCurrentProcess().SessionId

The value is the same as returned by GetTokenInformation(...,TokenSessionId,...).

Note: One thing you should keep in mind is that Session Id is not a Logon Id. For example, on Win7 elevated process launched under the same user in the same session will have different LogonId (copmaring to non-elevated one), but will have the same SessionId. Even runniung non-elevated process with RunAs explicitly specifying credentials of the same user will create new Logon Sesison Id. Such behavior has meaning, for example, when you map network drives. Since Vista, a process with one token LogonId will not see network dirves mapped with another LogonId, even if processes are running in the same session and under same user.

Below is the sample app that you can launch on different sessions/creds to see the difference:

using System;
using System.Runtime.InteropServices;

namespace GetCurrentSessionId
{
    class Program
    {

        enum TokenInformationClass
        {
            TokenUser = 1,
            TokenGroups,
            TokenPrivileges,
            TokenOwner,
            TokenPrimaryGroup,
            TokenDefaultDacl,
            TokenSource,
            TokenType,
            TokenImpersonationLevel,
            TokenStatistics,
            TokenRestrictedSids,
            TokenSessionId,
            TokenGroupsAndPrivileges,
            TokenSessionReference,
            TokenSandBoxInert,
            TokenAuditPolicy,
            TokenOrigin
        }

        enum TokenType
        {
            TokenPrimary = 1, 
            TokenImp
answered 2013-06-05T14:30:54.777

Your Answer