[英]Dynamic impersonation in asp.net
有沒有辦法在asp.net中動態模仿用戶? 我需要在每個請求的上下文中進行模擬,因為模擬的用戶每次都可能不同。 這就是為什么我不能使用web.config,因為它將適用於所有請求。
我不記得我上課的地方。 但這應該對你有好處。
using System;
using System.Security.Principal;
using System.Runtime.InteropServices;
public class Impersonation
{
public static int LOGON32_LOGON_INTERACTIVE = 2;
public static int LOGON32_PROVIDER_DEFAULT = 0;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(string lpxzUsername, string lpzDomain, string lpzPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll")]
public static extern int DuplicateToken(IntPtr ExistingTokenHandle, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll")]
public static extern long RevertToSelf();
[DllImport("Kernel32.dll")]
public static extern long CloseHandle(IntPtr handle);
public static WindowsImpersonationContext impersonationContext;
public static bool impersonateValidUser(string userName, string domain, string password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
bool ValidUser = false;
if (RevertToSelf() != 0)
{
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)
{
ValidUser = true;
}
}
}
}
if (!tokenDuplicate.Equals(IntPtr.Zero))
{
CloseHandle(tokenDuplicate);
}
if (!token.Equals(IntPtr.Zero))
{
CloseHandle(token);
}
return ValidUser;
}
public static void undoImpersonation()
{
try
{
impersonationContext.Undo();
}
catch
{
}
}
}
然后你就這樣稱呼它
Impersonation.impersonateValidUser("user", "domain", "password");
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.