asp.net中的动态模拟

时间:2012-01-26 16:25:02

标签: asp.net security impersonation

有没有办法在asp.net中动态模仿用户?我需要在每个请求的上下文中进行模拟,因为模拟的用户每次都可能不同。这就是我不能使用web.config的原因,因为它适用于所有请求。

1 个答案:

答案 0 :(得分:2)

我不记得我上课的地方。但这对你有用。

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");

希望它有所帮助。