我相信應用程序將以應用程序池的標識運行。爲了以不同身份運行,您需要模擬用戶。 MSDN有一篇關於它的文章。這是我根據幫助我完成類似事情的文章寫的一堂課。
class Impersonator : IDisposable
{
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);
WindowsIdentity newId;
WindowsImpersonationContext impersonatedUser;
private bool isDisposed;
public Impersonator(string user, string password, string domain)
{
SafeTokenHandle safeTokenHandle;
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
impersonatedUser = newId.Impersonate();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
if (impersonatedUser != null)
{
this.impersonatedUser.Dispose();
}
if (newId != null)
{
this.newId.Dispose();
}
}
}
this.isDisposed = true;
}
~Impersonator()
{
Dispose(false);
}
private sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
}
基本上,當你想模仿用戶並在完成後處置類時,創建類的新實例。
我希望這有助於!
什麼類型的用戶管理組.. ..?這是任何用戶..?如果是這樣'BAD IDEA'爲什麼你沒有一個AD管理組管理..?而另一件事情是,您仍然可以獲取機器的當前用戶並將其保留在不同的會話中,然後再解決您嘗試模擬的服務帳戶或帳戶用戶。 – MethodMan
只有組管理員才能編輯成員資格。在解析到服務帳戶之前,我將如何訪問當前計算機的用戶? –
'var currUser = System.Security.Principal.WindowsIdentity.GetCurrent()。Name.Split('\\');' – MethodMan