Back to "- 背面和冒充用户的代码..."

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

C# Imported mostlylucidcouk Security

- 背面和冒充用户的代码...

Monday, 06 October 2008

那么,有一个可爱的突破... 现在一些代码, 这将让你"冒名顶替"一个用户 - 真的很方便,例如,当尝试上传文件 到网络位置...

using System;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;

namespace Components.Security
{
    /// 
    /// Summary description for ImpersonateUser.
    /// 
    public class ImpersonateUser
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        WindowsImpersonationContext impersonationContext;
        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
            public static extern int LogonUser(    string lpszUserUname,
                                                string lpszDomain,
                                                string lpszPassword,
                                                int dwLogonType,
                                                int dwLogonProvider,
                                                ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
            public extern static int DuplicateToken(IntPtr hToken,
                                                    int impersonationLevel,
                                                    ref IntPtr hNewToken);
        public bool impersonateValidUser(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if(LogonUser(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();
                    return (impersonationContext != null);                    
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        public void undoImpersonation()
        {
            impersonationContext.Undo();
        }
        
    }
}
logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.