爲了防止其他人遇到同樣的問題,我有,這是一個可行的答案。大部分代碼都是從MSDN網站上獲取的......它的工作原理。但基本上你想要做的是冒充你需要的用戶。
這些添加到您的usings,
using System.Web.Security;
using System.Runtime.InteropServices;
using System.Security.Principal;
寫下面的方法:
private bool impersonateValidUser(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;
}
落實在需要的地方
if (impersonateValidUser("username", "domain", "password"))
{
// code that needs to access Db
// make sure you undo when no longer needed
impersonationContext.Undo();
}
是你的SQL用戶名和連接字符串中指定的密碼,或你依靠Windows身份驗證嗎? – 2011-12-15 17:15:35