Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

后端 未结 10 1209
走了就别回头了
走了就别回头了 2020-11-22 05:12

We\'ve run into an interesting situation that needs solving, and my searches have turned up nill. I therefore appeal to the SO community for help.

The issue is this:

10条回答
  •  天命终不由人
    2020-11-22 05:46

    While I don't know myself, I would certainly hope that #2 is incorrect...I'd like to think that Windows isn't going to AUTOMATICALLY give out my login information (least of all my password!) to any machine, let alone one that isn't part of my trust.

    Regardless, have you explored the impersonation architecture? Your code is going to look similar to this:

    using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(token))
    {
        // Do network operations here
    
        context.Undo();
    }
    

    In this case, the token variable is an IntPtr. In order to get a value for this variable, you'll have to call the unmanaged LogonUser Windows API function. A quick trip to pinvoke.net gives us the following signature:

    [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(
        string lpszUsername,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        out IntPtr phToken
    );
    

    Username, domain, and password should seem fairly obvious. Have a look at the various values that can be passed to dwLogonType and dwLogonProvider to determine the one that best suits your needs.

    This code hasn't been tested, as I don't have a second domain here where I can verify, but this should hopefully put you on the right track.

提交回复
热议问题