活动目录辅助类

来源:互联网 发布:mac os 文件夹加密 编辑:程序博客网 时间:2024/04/30 17:47
  1. using System;
  2. using System.DirectoryServices;
  3. namespace SystemFrameworks.Helper
  4. {
  5.    ///
  6.    /// 活动目录辅助类。封装一系列活动目录操作相关的方法。
  7.    ///
  8.    public sealed class ADHelper
  9.    {
  10.    ///
  11.    /// 域名
  12.    ///
  13.    private static string DomainName = "MyDomain";
  14.    ///
  15.    /// LDAP 地址
  16.    ///
  17.    private static string LDAPDomain = "DC=MyDomain,DC=local";
  18.    ///
  19.    /// LDAP绑定路径
  20.    ///
  21.    private static string ADPath = "LDAP://brooks.mydomain.local";
  22.    ///
  23.    /// 登录帐号
  24.    ///
  25.    private static string ADUser = "Administrator";
  26.    ///
  27.    /// 登录密码
  28.    ///
  29.    private static string ADPassword = "password";
  30.    ///
  31.    /// 扮演类实例
  32.    ///
  33.    private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
  34.    ///
  35.    /// 用户登录验证结果
  36.    ///
  37.    public enum LoginResult
  38.    {
  39.    ///
  40.    /// 正常登录
  41.    ///
  42.    LOGIN_USER_OK = 0,
  43.    ///
  44.    /// 用户不存在
  45.    ///
  46.    LOGIN_USER_DOESNT_EXIST,
  47.    ///
  48.    /// 用户帐号被禁用
  49.    ///
  50.    LOGIN_USER_ACCOUNT_INACTIVE,
  51.    ///
  52.    /// 用户密码不正确
  53.    ///
  54.    LOGIN_USER_PASSWORD_INCORRECT
  55.    }
  56.    ///
  57.    /// 用户属性定义标志
  58.    ///
  59.    public enum ADS_USER_FLAG_ENUM
  60.    {
  61.    ///
  62.    /// 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。
  63.    ///
  64.    ADS_UF_SCRIPT = 0X0001,
  65.    ///
  66.    /// 用户帐号禁用标志
  67.    ///
  68.    ADS_UF_ACCOUNTDISABLE = 0X0002,
  69.    ///
  70.    /// 主文件夹标志
  71.    ///
  72.    ADS_UF_HOMEDIR_REQUIRED = 0X0008,
  73.    ///
  74.    /// 过期标志
  75.    ///
  76.    ADS_UF_LOCKOUT = 0X0010,
  77.    ///
  78.    /// 用户密码不是必须的
  79.    ///
  80.    ADS_UF_PASSWD_NOTREQD = 0X0020,
  81.    ///
  82.    /// 密码不能更改标志
  83.    ///
  84.    ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
  85.    ///
  86.    /// 使用可逆的加密保存密码
  87.    ///
  88.    ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
  89.    ///
  90.    /// 本地帐号标志
  91.    ///
  92.    ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
  93.    ///
  94.    /// 普通用户的默认帐号类型
  95.    ///
  96.    ADS_UF_NORMAL_ACCOUNT = 0X0200,
  97.    ///
  98.    /// 跨域的信任帐号标志
  99.    ///
  100.    ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
  101.    ///
  102.    /// 工作站信任帐号标志
  103.    ///
  104.    ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
  105.    ///
  106.    /// 服务器信任帐号标志
  107.    ///
  108.    ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
  109.    ///
  110.    /// 密码永不过期标志
  111.    ///
  112.    ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
  113.    ///
  114.    /// MNS 帐号标志
  115.    ///
  116.    ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
  117.    ///
  118.    /// 交互式登录必须使用智能卡
  119.    ///
  120.    ADS_UF_SMARTCARD_REQUIRED = 0X40000,
  121.    ///
  122.    /// 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
  123.    ///
  124.    ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
  125.    ///
  126.    /// 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
  127.    ///
  128.    ADS_UF_NOT_DELEGATED = 0X100000,
  129.    ///
  130.    /// 此帐号需要 DES 加密类型
  131.    ///
  132.    ADS_UF_USE_DES_KEY_ONLY = 0X200000,
  133.    ///
  134.    /// 不要进行 Kerberos 预身份验证
  135.    ///
  136.    ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
  137.    ///
  138.    /// 用户密码过期标志
  139.    ///
  140.    ADS_UF_PASSWORD_EXPIRED = 0X800000,
  141.    ///
  142.    /// 用户帐号可委托标志
  143.    ///
  144.    ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
  145.    }
  146.    public ADHelper()
  147.    {
  148.    //
  149.    }
  150.    #region GetDirectoryObject
  151.    ///
  152.    /// 获得DirectoryEntry对象实例,以管理员登陆AD
  153.    ///
  154.    ///
  155.    private static DirectoryEntry GetDirectoryObject()
  156.    {
  157.    DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
  158.    return entry;
  159.    }
  160.    ///
  161.    /// 根据指定用户名和密码获得相应DirectoryEntry实体
  162.    ///
  163.    ///
  164.    ///
  165.    ///
  166.    private static DirectoryEntry GetDirectoryObject(string userName, string password)
  167.    {
  168.    DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);
  169.    return entry;
  170.    }
  171.    ///
  172.    /// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com
  173.    ///
  174.    ///
  175.    ///
  176.    private static DirectoryEntry GetDirectoryObject(string domainReference)
  177.    {
  178.    DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);
  179.    return entry;
  180.    }
  181.    ///
  182.    /// 获得以UserName,Password创建的DirectoryEntry
  183.    ///
  184.    ///
  185.    ///
  186.    ///
  187.    ///
  188.    private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
  189.    {
  190.    DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
  191.    return entry;
  192.    }
  193.    #endregion
  194.    #region GetDirectoryEntry
  195.    ///
  196.    /// 根据用户公共名称取得用户的 对象
  197.    ///
  198.    /// 用户公共名称
  199.    /// 如果找到该用户,则返回用户的 对象否则返回 null
  200.    public static DirectoryEntry GetDirectoryEntry(string commonName)
  201.    {
  202.    DirectoryEntry de = GetDirectoryObject();
  203.    DirectorySearcher deSearch = new DirectorySearcher(de);
  204.    deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
  205.    deSearch.SearchScope = SearchScope.Subtree;
  206.    try
  207.    {
  208.    SearchResult result = deSearch.FindOne();
  209.    de = new DirectoryEntry(result.Path);
  210.    return de;
  211.    }
  212.    catch
  213.    {
  214.    return null;
  215.    }
  216.    }
  217.    ///
  218.    /// 根据用户公共名称和密码取得用户的 对象。
  219.    ///
  220.    /// 用户公共名称
  221.    /// 用户密码
  222.    /// 如果找到该用户,则返回用户的 对象否则返回 null
  223.    public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
  224.    {
  225.    DirectoryEntry de = GetDirectoryObject(commonName, password);
  226.    DirectorySearcher deSearch = new DirectorySearcher(de);
  227.    deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
  228.    deSearch.SearchScope = SearchScope.Subtree;
  229.    try
  230.    {
  231.    SearchResult result = deSearch.FindOne();
  232.    de = new DirectoryEntry(result.Path);
  233.    return de;
  234.    }
  235.    catch
  236.    {
  237.    return null;
  238.    }
  239.    }
  240.    ///
  241.    /// 根据用户帐号称取得用户的 对象
  242.    ///
  243.    /// 用户帐号名
  244.    /// 如果找到该用户,则返回用户的 对象否则返回 null
  245.    public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
  246.    {
  247.    DirectoryEntry de = GetDirectoryObject();
  248.    DirectorySearcher deSearch = new DirectorySearcher(de);
  249.    deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
  250.    deSearch.SearchScope = SearchScope.Subtree;
  251.    try
  252.    {
  253.    SearchResult result = deSearch.FindOne();
  254.    de = new DirectoryEntry(result.Path);
  255.    return de;
  256.    }
  257.    catch
  258.    {
  259.    return null;
  260.    }
  261.    }
  262.    ///
  263.    /// 根据用户帐号和密码取得用户的 对象
  264.    ///
  265.    /// 用户帐号名
  266.    /// 用户密码
  267.    /// 如果找到该用户,则返回用户的 对象否则返回 null
  268.    public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
  269.    {
  270.    DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
  271.    if (de != null)
  272.    {
  273.    string commonName = de.Properties["cn"][0].ToString();
  274.    if (GetDirectoryEntry(commonName, password) != null)
  275.    return GetDirectoryEntry(commonName, password);
  276.    else
  277.    return null;
  278.    }
  279.    else
  280.    {
  281.    return null;
  282.    }
  283.    }
  284.    ///
  285.    /// 根据组名取得用户组的 对象
  286.    ///
  287.    /// 组名
  288.    ///
  289.    public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
  290.    {
  291.    DirectoryEntry de = GetDirectoryObject();
  292.    DirectorySearcher deSearch = new DirectorySearcher(de);
  293.    deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
  294.    deSearch.SearchScope = SearchScope.Subtree;
  295.    try
  296.    {
  297.    SearchResult result = deSearch.FindOne();
  298.    de = new DirectoryEntry(result.Path);
  299.    return de;
  300.    }
  301.    catch
  302.    {
  303.    return null;
  304.    }
  305.    }
  306.    #endregion
  307.    #region GetProperty
  308.    ///
  309.    /// 获得指定 指定属性名对应的值
  310.    ///
  311.    ///
  312.    /// 属性名称
  313.    /// 属性值
  314.    public static string GetProperty(DirectoryEntry de, string propertyName)
  315.    {
  316.    if(de.Properties.Contains(propertyName))
  317.    {
  318.    return de.Properties[propertyName][0].ToString() ;
  319.    }
  320.    else
  321.    {
  322.    return string.Empty;
  323.    }
  324.    }
  325.    ///
  326.    /// 获得指定搜索结果 中指定属性名对应的值
  327.    ///
  328.    ///
  329.    /// 属性名称
  330.    /// 属性值
  331.    public static string GetProperty(SearchResult searchResult, string propertyName)
  332.    {
  333.    if(searchResult.Properties.Contains(propertyName))
  334.    {
  335.    return searchResult.Properties[propertyName][0].ToString() ;
  336.    }
  337.    else
  338.    {
  339.    return string.Empty;
  340.    }
  341.    }
  342.    #endregion
  343.    ///
  344.    /// 设置指定 的属性值
  345.    ///
  346.    ///
  347.    /// 属性名称
  348.    /// 属性值
  349.    public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
  350.    {
  351.    if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
  352.    {
  353.    if(de.Properties.Contains(propertyName))
  354.    {
  355.    de.Properties[propertyName][0] = propertyValue;
  356.    }
  357.    else
  358.    {
  359.    de.Properties[propertyName].Add(propertyValue);
  360.    }
  361.    }
  362.    }
  363.    ///
  364.    /// 创建新的用户
  365.    ///
  366.    /// DN 位置。例如:OU=共享平台 或 CN=Users
  367.    /// 公共名称
  368.    /// 帐号
  369.    /// 密码
  370.    ///
  371.    public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
  372.    {
  373.    DirectoryEntry entry = GetDirectoryObject();
  374.    DirectoryEntry subEntry = entry.Children.Find(ldapDN);
  375.    DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
  376.    deUser.Properties["sAMAccountName"].Value = sAMAccountName;
  377.    deUser.CommitChanges();
  378.    ADHelper.EnableUser(commonName);
  379.    ADHelper.SetPassword(commonName, password);
  380.    deUser.Close();
  381.    return deUser;
  382.    }
  383.    ///
  384.    /// 创建新的用户。默认创建在 Users 单元下。
  385.    ///
  386.    /// 公共名称
  387.    /// 帐号
  388.    /// 密码
  389.    ///
  390.    public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)
  391.    {
  392.    return CreateNewUser("CN=Users", commonName, sAMAccountName, password);
  393.    }
  394.    ///
  395.    /// 判断指定公共名称的用户是否存在
  396.    ///
  397.    /// 用户公共名称
  398.    /// 如果存在,返回 true否则返回 false
  399.    public static bool IsUserExists(string commonName)
  400.    {
  401.    DirectoryEntry de = GetDirectoryObject();
  402.    DirectorySearcher deSearch = new DirectorySearcher(de);
  403.    deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))"// LDAP 查询串
  404.    SearchResultCollection results = deSearch.FindAll();
  405.    if (results.Count == 0)
  406.    return false;
  407.    else
  408.    return true;
  409.    }
  410.    ///
  411.    /// 判断用户帐号是否激活
  412.    ///
  413.    /// 用户帐号属性控制器
  414.    /// 如果用户帐号已经激活,返回 true否则返回 false
  415.    public static bool IsAccountActive(int userAccountControl)
  416.    {
  417.    int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
  418.    int flagExists = userAccountControl & userAccountControl_Disabled;
  419.    if (flagExists 〉 0)
  420.    return false;
  421.    else
  422.    return true;
  423.    }
  424.    ///
  425.    /// 判断用户与密码是否足够以满足身份验证进而登录
  426.    ///
  427.    /// 用户公共名称
  428.    /// 密码
  429.    /// 如能可正常登录,则返回 true否则返回 false
  430.    public static LoginResult Login(string commonName, string password)
  431.    {
  432.    DirectoryEntry de = GetDirectoryEntry(commonName);
  433.    if (de != null)
  434.    {
  435.    // 必须在判断用户密码正确前,对帐号激活属性进行判断否则将出现异常。
  436.    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
  437.    de.Close();
  438.    if (!IsAccountActive(userAccountControl))
  439.    return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
  440.    if (GetDirectoryEntry(commonName, password) != null)
  441.    return LoginResult.LOGIN_USER_OK;
  442.    else
  443.    return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
  444.    }
  445.    else
  446.    {
  447.    return LoginResult.LOGIN_USER_DOESNT_EXIST;
  448.    }
  449.    }
  450.    ///
  451.    /// 判断用户帐号与密码是否足够以满足身份验证进而登录
  452.    ///
  453.    /// 用户帐号
  454.    /// 密码
  455.    /// 如能可正常登录,则返回 true否则返回 false
  456.    public static LoginResult LoginByAccount(string sAMAccountName, string password)
  457.    {
  458.    DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
  459.   
  460.    if (de != null)
  461.    {
  462.    // 必须在判断用户密码正确前,对帐号激活属性进行判断否则将出现异常。
  463.    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
  464.    de.Close();
  465.    if (!IsAccountActive(userAccountControl))
  466.    return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;
  467.    if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
  468.    return LoginResult.LOGIN_USER_OK;
  469.    else
  470.    return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
  471.    }
  472.    else
  473.    {
  474.    return LoginResult.LOGIN_USER_DOESNT_EXIST;
  475.    }
  476.    }
  477.    ///
  478.    /// 设置用户密码,管理员可以通过它来修改指定用户的密码。
  479.    ///
  480.    /// 用户公共名称
  481.    /// 用户新密码
  482.    public static void SetPassword(string commonName, string newPassword)
  483.    {
  484.    DirectoryEntry de = GetDirectoryEntry(commonName);
  485.   
  486.    // 模拟超级管理员,以达到有权限修改用户密码
  487.    impersonate.BeginImpersonate();
  488.    de.Invoke("SetPassword"new object[]{newPassword});
  489.    impersonate.StopImpersonate();
  490.    de.Close();
  491.    }
  492.    ///
  493.    /// 设置帐号密码,管理员可以通过它来修改指定帐号的密码。
  494.    ///
  495.    /// 用户帐号
  496.    /// 用户新密码
  497.    public static void SetPasswordByAccount(string sAMAccountName, string newPassword)
  498.    {
  499.    DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
  500.    // 模拟超级管理员,以达到有权限修改用户密码
  501.    IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
  502.    impersonate.BeginImpersonate();
  503.    de.Invoke("SetPassword"new object[]{newPassword});
  504.    impersonate.StopImpersonate();
  505.    de.Close();
  506.    }
  507.    ///
  508.    /// 修改用户密码
  509.    ///
  510.    /// 用户公共名称
  511.    /// 旧密码
  512.    /// 新密码
  513.    public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword)
  514.    {
  515.    // to-do: 需要解决密码策略问题
  516.    DirectoryEntry oUser = GetDirectoryEntry(commonName);
  517.    oUser.Invoke("ChangePassword"new Object[]{oldPassword, newPassword});
  518.    oUser.Close();
  519.    }
  520.    ///
  521.    /// 启用指定公共名称的用户
  522.    ///
  523.    /// 用户公共名称
  524.    public static void EnableUser(string commonName)
  525.    {
  526.    EnableUser(GetDirectoryEntry(commonName));
  527.    }
  528.    ///
  529.    /// 启用指定 的用户
  530.    ///
  531.    ///
  532.    public static void EnableUser(DirectoryEntry de)
  533.    {
  534.    impersonate.BeginImpersonate();
  535.    de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
  536.    de.CommitChanges();
  537.    impersonate.StopImpersonate();
  538.    de.Close();
  539.    }
  540.    ///
  541.    /// 禁用指定公共名称的用户
  542.    ///
  543.    /// 用户公共名称
  544.    public static void DisableUser(string commonName)
  545.    {
  546.    DisableUser(GetDirectoryEntry(commonName));
  547.    }
  548.    ///
  549.    /// 禁用指定 的用户
  550.    ///
  551.    ///
  552.    public static void DisableUser(DirectoryEntry de)
  553.    {
  554.    impersonate.BeginImpersonate();
  555.    de.Properties["userAccountControl"][0]=ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
  556.    de.CommitChanges();
  557.    impersonate.StopImpersonate();
  558.    de.Close();
  559.    }
  560.    ///
  561.    /// 将指定的用户添加到指定的组中。默认为 Users 下的组和用户。
  562.    ///
  563.    /// 用户公共名称
  564.    /// 组名
  565.    public static void AddUserToGroup(string userCommonName, string groupName)
  566.    {
  567.    DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
  568.    DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
  569.   
  570.    impersonate.BeginImpersonate();
  571.    oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
  572.    oGroup.CommitChanges();
  573.    impersonate.StopImpersonate();
  574.    oGroup.Close();
  575.    oUser.Close();
  576.    }
  577.    ///
  578.    /// 将用户从指定组中移除。默认为 Users 下的组和用户。
  579.    ///
  580.    /// 用户公共名称
  581.    /// 组名
  582.    public static void RemoveUserFromGroup(string userCommonName, string groupName)
  583.    {
  584.    DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
  585.    DirectoryEntry oUser = GetDirectoryEntry(userCommonName);
  586.   
  587.    impersonate.BeginImpersonate();
  588.    oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
  589.    oGroup.CommitChanges();
  590.    impersonate.StopImpersonate();
  591.    oGroup.Close();
  592.    oUser.Close();
  593.    }
  594.    }
  595.    ///
  596.    /// 用户模拟角色类。实现在程序段内进行用户角色模拟。
  597.    ///
  598.    public class IdentityImpersonation
  599.    {
  600.    [DllImport("advapi32.dll", SetLastError=true)]
  601.    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  602.    [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
  603.    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
  604.    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
  605.    public extern static bool CloseHandle(IntPtr handle);
  606.    // 要模拟的用户的用户名、密码、域(机器名)
  607.    private String _sImperUsername;
  608.    private String _sImperPassword;
  609.    private String _sImperDomain;
  610.    // 记录模拟上下文
  611.    private WindowsImpersonationContext _imperContext;
  612.    private IntPtr _adminToken;
  613.    private IntPtr _dupeToken;
  614.    // 是否已停止模拟
  615.    private Boolean _bClosed;
  616.    ///
  617.    /// 构造函数
  618.    ///
  619.    /// 所要模拟的用户的用户名
  620.    /// 所要模拟的用户的密码
  621.    /// 所要模拟的用户所在的域
  622.    public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
  623.    {
  624.    _sImperUsername = impersonationUsername;
  625.    _sImperPassword = impersonationPassword;
  626.    _sImperDomain = impersonationDomain;
  627.    _adminToken = IntPtr.Zero;
  628.    _dupeToken = IntPtr.Zero;
  629.    _bClosed = true;
  630.    }
  631.    ///
  632.    /// 析构函数
  633.    ///
  634.    ~IdentityImpersonation()
  635.    {
  636.    if(!_bClosed)
  637.    {
  638.    StopImpersonate();
  639.    }
  640.    }
  641.    ///
  642.    /// 开始身份角色模拟。
  643.    ///
  644.    ///
  645.    public Boolean BeginImpersonate()
  646.    {
  647.    Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);
  648.   
  649.    if(!bLogined)
  650.    {
  651.    return false;
  652.    }
  653.    Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);
  654.    if(!bDuped)
  655.    {
  656.    return false;
  657.    }
  658.    WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
  659.    _imperContext = fakeId.Impersonate();
  660.    _bClosed = false;
  661.    return true;
  662.    }
  663.    ///
  664.    /// 停止身分角色模拟。
  665.    ///
  666.    public void StopImpersonate()
  667.    {
  668.    _imperContext.Undo();
  669.    CloseHandle(_dupeToken);
  670.    CloseHandle(_adminToken);
  671.    _bClosed = true;
  672.    }
  673.    }
  674. }

原创粉丝点击