【问题标题】:RW access to shared Windows folder using different user credentials in .NET使用 .NET 中的不同用户凭据对共享 Windows 文件夹进行 RW 访问
【发布时间】:2011-02-20 21:54:47
【问题描述】:

我们在 Windows 网络中工作(正在使用 AD)
我们有用户共享的文件夹(仅限此用户的访问权限) 用户凭据是已知的 我需要在我的应用程序中访问该共享。

注意我已经阅读了关于 Impersonation 但我可以做的是在新用户上下文中打开整个应用程序(但我需要作为当前登录的用户工作,只需访问 Windows 的共享文件夹代表另一个用户)

这可能吗?一段代码赞赏..

【问题讨论】:

  • 你有没有运气解决这个问题?
  • 是的,我做到了。请看下面我的回答

标签: c# .net-3.5 active-directory impersonation


【解决方案1】:

我终于做到了,这对我有害!
对于那些有兴趣的人 - 请找到执行工作的示例方法(注意您需要 System.Security.Principal + Interop,还需要添加一些 API 静态方法)

    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;

    public bool ImpersonateUser( string userName, string domain, string password ) {
        WindowsIdentity tempWindowsIdentity;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        if (RevertToSelf ()) {
            if (LogonUserA ( userName, domain, 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 true;
                    }
                }
            }
        }
        if (token!= IntPtr.Zero)
            CloseHandle ( token );
        if (tokenDuplicate!=IntPtr.Zero)
            CloseHandle ( tokenDuplicate );
        return false;
    }

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2021-12-26
    • 2011-11-25
    相关资源
    最近更新 更多