How to get the current Windows user's *network* identity, not their interactive log-on identity?

StackOverflow https://stackoverflow.com/questions/13094142

سؤال

Question:

What is the .NET (or p/invoke to an unmanaged Windows API) method call to get the current process's network identity that is used to connect to SSPI-authenticated network services, such as SQL Server?


The specific use-case I have in mind is where one can work on a non-domain-joined machine and use runas /noprofile /netonly /USER:DOMAIN\username to launch a process which uses that DOMAIN\username identity for network authentication instead of their local MACHINE\username logged-on identity.

I want the method call that gives me the DOMAIN\username identity passed to RUNAS here.

Thanks!


To be clear, I am NOT looking for the method call to get the current user's locally logged on identity (which may be different than the network identity). This excludes System.Security.Principal.WindowsIdentity.GetCurrent().Name and Environment.UserName and probably System.Threading.Thread.CurrentPrincipal.Identity.Name from being accepted answers. I will downvote any answer that incorrectly indicates any of these to be the solution, unless I am shown to be wrong here of course. :)

هل كانت مفيدة؟

المحلول

This prints the user (in the form "user@domain") for outbound connections. It's C++.

CredHandle credHandle;
TimeStamp timeStamp;
SECURITY_STATUS status = AcquireCredentialsHandle(0, L"Negotiate", SECPKG_CRED_OUTBOUND, 0, 0, 0, 0, &credHandle, &timeStamp);
if (status == SEC_E_OK)
{
    SecPkgCredentials_Names names;
    status = QueryCredentialsAttributes(&credHandle, SECPKG_CRED_ATTR_NAMES, &names);
    if (status == SEC_E_OK)
    {
        wprintf(L"%s\n", names.sUserName);
        status = FreeContextBuffer(names.sUserName);
    }
    status = FreeCredentialsHandle(&credHandle);
}

Some other information: I guess runas is using CreateProcessWithLogonW with the LOGON_NETCREDENTIALS_ONLY flag. This creates a new logon session based on the existing logon session, with the net credentials hidden inside it. GetTokenInformation and LsaGetLogonSessionData return information about the original user, not the network user. The one bit of Windows that must know about the network user is SSPI, so that it can send the user name and domain to the remote server. Hence the code above.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top