Impersonate a user on another domain, one way trus

2019-08-29 18:12发布

I am attempting to impersonate a user on another domain, for the purpose of querying that domain. See Accessing user info from a one way trust for some background.

My impersonation works correctly when I'm using a local domain user. When I specify the target domain, which is also over LDAPS port 636, it doesn't work. My impersonation returns null.

My Impersonation Code

public static WindowsImpersonationContext ImpersonateUser(ConnectionCredentials user)
    {
        WindowsIdentity tempWindowsIdentity;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf())
        {
            if (LogonUser(user.UserName, user.Domain, user.Password, LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                {
                    tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                    impersonationContext = tempWindowsIdentity.Impersonate();
                    if (impersonationContext != null)
                    {
                        CloseHandle(token);
                        CloseHandle(tokenDuplicate);
                        return impersonationContext;
                    }
                }
            }
        }
        if (token != IntPtr.Zero)
            CloseHandle(token);
        if (tokenDuplicate != IntPtr.Zero)
            CloseHandle(tokenDuplicate);
        return impersonationContext;
    }

Any ideas? Thanks.

1条回答
混吃等死
2楼-- · 2019-08-29 19:11

My issue was that I was sending in the user name as username@domain, AND specifying the domain name. In the event the user name contains the domain name, the domain name for LogonUser needs to be null

if (LogonUser(user.UserName, null, user.Password, LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, ref token) != 0)

Thanks!

查看更多
登录 后发表回答