繁体   English   中英

asp.net中的动态模拟

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM