在开发过程中,常常遇到这样的问题:文件,包括图片和文件上传到服务器,而Web服务器和文件服务器不是同一个,而且不在同一个域里面,那么针对于.NET应该如何处理这样的问题呢? 可能很多高手一下子就知道如何解决,但是我确实是经过了一番努力才弄明白,下面就结束如何使用.NET的Windows模拟身份验证。 1、首先引用两个名称空间
using System.Security.Principal; using System.Runtime.InteropServices; 2、其次定义好模拟权限的调用方法
region 权限模拟 public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError = true)] public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);<summary>/// 验证用户,并生成WindowsIdentity 实例 </summary>private static WindowsIdentity GetIdentity(String userName, String domain, String password) { IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) == 0) return null; else if (DuplicateToken(token, 2, ref tokenDuplicate) == 0) return null; else return new WindowsIdentity(tokenDuplicate); } public WindowsImpersonationContext GetContext() { WindowsIdentity identity = null; WindowsImpersonationContext impersonationContext = null; identity = string.IsNullOrEmpty(user) ? null : GetIdentity(user, null, pwd); // 使用用户凭证进行用户模拟 impersonationContext = (identity == null) ? null : identity.Impersonate(); return impersonationContext; } #endregion 3、在调用身份模拟的函数中使用
...