1. using System; 
  2. using System.DirectoryServices; 
  3.   
  4. namespace SystemFrameworks.Helper 
  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.          /// 
  38.          public enum LoginResult 
  39.          { 
  40.               /// 
  41.               ///正常登录 
  42.               /// 
  43.               LOGIN_USER_OK = 0, 
  44.               /// 
  45.               ///用户不存在 
  46.               /// 
  47.               LOGIN_USER_DOESNT_EXIST, 
  48.               /// 
  49.               ///用户帐号被禁用 
  50.               /// 
  51.               LOGIN_USER_ACCOUNT_INACTIVE, 
  52.               /// 
  53.               ///用户密码不正确 
  54.               /// 
  55.               LOGIN_USER_PASSWORD_INCORRECT 
  56.          } 
  57.   
  58.          /// 
  59.          ///用户属性定义标志 
  60.          /// 
  61.          public enum ADS_USER_FLAG_ENUM 
  62.          { 
  63.               /// 
  64.               ///登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。 
  65.               /// 
  66.               ADS_UF_SCRIPT = 0X0001, 
  67.               /// 
  68.               ///用户帐号禁用标志 
  69.               /// 
  70.               ADS_UF_ACCOUNTDISABLE = 0X0002, 
  71.               /// 
  72.               ///主文件夹标志 
  73.               /// 
  74.               ADS_UF_HOMEDIR_REQUIRED = 0X0008, 
  75.               /// 
  76.               ///过期标志 
  77.               /// 
  78.               ADS_UF_LOCKOUT = 0X0010, 
  79.               /// 
  80.               ///用户密码不是必须的 
  81.               /// 
  82.               ADS_UF_PASSWD_NOTREQD = 0X0020, 
  83.               /// 
  84.               ///密码不能更改标志 
  85.               /// 
  86.               ADS_UF_PASSWD_CANT_CHANGE = 0X0040, 
  87.               /// 
  88.               ///使用可逆的加密保存密码 
  89.               /// 
  90. ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
  91.               /// 
  92.               ///本地帐号标志 
  93.               /// 
  94.               ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100, 
  95.               /// 
  96.               ///普通用户的默认帐号类型 
  97.               /// 
  98.               ADS_UF_NORMAL_ACCOUNT = 0X0200, 
  99.               /// 
  100.               ///跨域的信任帐号标志 
  101.               /// 
  102.               ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800, 
  103.               /// 
  104.               ///工作站信任帐号标志 
  105.               /// 
  106.               ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000, 
  107.               /// 
  108.               ///服务器信任帐号标志 
  109.               /// 
  110.               ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000, 
  111.               /// 
  112.               ///密码永不过期标志 
  113.               /// 
  114.               ADS_UF_DONT_EXPIRE_PASSWD = 0X10000, 
  115.               /// 
  116.               /// MNS 帐号标志 
  117.               /// 
  118.               ADS_UF_MNS_LOGON_ACCOUNT = 0X20000, 
  119.               /// 
  120.               ///交互式登录必须使用智能卡 
  121.               /// 
  122.               ADS_UF_SMARTCARD_REQUIRED = 0X40000, 
  123.               /// 
  124.               ///当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任 
  125.               /// 
  126.               ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000, 
  127.               /// 
  128.               ///当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托 
  129.               /// 
  130.               ADS_UF_NOT_DELEGATED = 0X100000, 
  131.               /// 
  132.               ///此帐号需要 DES 加密类型 
  133.               /// 
  134.               ADS_UF_USE_DES_KEY_ONLY = 0X200000, 
  135.               /// 
  136.               ///不要进行 Kerberos 预身份验证 
  137.               /// 
  138.               ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000, 
  139.               /// 
  140.               ///用户密码过期标志 
  141.               /// 
  142.               ADS_UF_PASSWORD_EXPIRED = 0X800000, 
  143.               /// 
  144.               ///用户帐号可委托标志 
  145.               /// 
  146.               ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000 
  147.          } 
  148.   
  149.          public ADHelper() 
  150.          { 
  151.               // 
  152.          } 
  153.          #region GetDirectoryObject 
  154.   
  155.          /// 
  156.          ///获得DirectoryEntry对象实例,以管理员登陆AD 
  157.          /// 
  158.          /// 
  159.          private static DirectoryEntry GetDirectoryObject() 
  160.          { 
  161.               DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
  162.               return entry; 
  163.          } 
  164.   
  165.          /// 
  166.          ///根据指定用户名和密码获得相应DirectoryEntry实体 
  167.          /// 
  168.          /// 
  169.          /// 
  170.          /// 
  171.          private static DirectoryEntry GetDirectoryObject(string userName, string password) 
  172.          { 
  173.               DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None); 
  174.               return entry; 
  175.          } 
  176.   
  177.          /// 
  178.          /// i.e. /CN=Users,DC=creditsights, DC=cyberelves, DC=Com 
  179.          /// 
  180.          /// 
  181.          /// 
  182.          private static DirectoryEntry GetDirectoryObject(string domainReference) 
  183.          { 
  184.               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure); 
  185.               return entry; 
  186.          } 
  187.   
  188.          /// 
  189.          ///获得以UserName,Password创建的DirectoryEntry 
  190.          /// 
  191.          /// 
  192.          /// 
  193.          /// 
  194.          /// 
  195.          private static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password) 
  196.          { 
  197.               DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure); 
  198.               return entry; 
  199.          } 
  200.          #endregion 
  201.          #region GetDirectoryEntry 
  202.   
  203.          /// 
  204.          ///根据用户公共名称取得用户的 对象 
  205.          /// 
  206.          /// 用户公共名称 
  207.          ///如果找到该用户,则返回用户的 对象;否则返回 null 
  208.          public static DirectoryEntry GetDirectoryEntry(string commonName) 
  209.          { 
  210.               DirectoryEntry de = GetDirectoryObject(); 
  211.               DirectorySearcher deSearch = new DirectorySearcher(de); 
  212.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))"
  213.               deSearch.SearchScope = SearchScope.Subtree; 
  214.   
  215.               try 
  216.               { 
  217.                    SearchResult result = deSearch.FindOne(); 
  218.                    de = new DirectoryEntry(result.Path); 
  219.                    return de; 
  220.               } 
  221.               catch 
  222.               { 
  223.                    return null
  224.               } 
  225.          } 
  226.   
  227.          /// 
  228.          ///根据用户公共名称和密码取得用户的 对象。 
  229.          /// 
  230.          /// 用户公共名称 
  231.          /// 用户密码 
  232.          ///如果找到该用户,则返回用户的 对象;否则返回 null 
  233.          public static DirectoryEntry GetDirectoryEntry(string commonName, string password) 
  234.          { 
  235.               DirectoryEntry de = GetDirectoryObject(commonName, password); 
  236.               DirectorySearcher deSearch = new DirectorySearcher(de); 
  237.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))"
  238.               deSearch.SearchScope = SearchScope.Subtree; 
  239.   
  240.               try 
  241.               { 
  242.                    SearchResult result = deSearch.FindOne(); 
  243.                    de = new DirectoryEntry(result.Path); 
  244.                    return de; 
  245.               } 
  246.               catch 
  247.               { 
  248.                    return null
  249.               } 
  250.          } 
  251.   
  252.          /// 
  253.          ///根据用户帐号称取得用户的 对象 
  254.          /// 
  255.          /// 用户帐号名 
  256.          ///如果找到该用户,则返回用户的 对象;否则返回 null 
  257.          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName) 
  258.          { 
  259.               DirectoryEntry de = GetDirectoryObject(); 
  260.               DirectorySearcher deSearch = new DirectorySearcher(de); 
  261.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))"
  262.               deSearch.SearchScope = SearchScope.Subtree; 
  263.   
  264.               try 
  265.               { 
  266.                    SearchResult result = deSearch.FindOne(); 
  267.                    de = new DirectoryEntry(result.Path); 
  268.                    return de; 
  269.               } 
  270.               catch 
  271.               { 
  272.                    return null
  273.               } 
  274.          } 
  275.   
  276.          /// 
  277.          ///根据用户帐号和密码取得用户的 对象 
  278.          /// 
  279.          /// 用户帐号名 
  280.          /// 用户密码 
  281.          ///如果找到该用户,则返回用户的 对象;否则返回 null 
  282.          public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password) 
  283.          { 
  284.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName); 
  285.               if (de != null
  286.               { 
  287.                    string commonName = de.Properties["cn"][0].ToString(); 
  288.   
  289.                    if (GetDirectoryEntry(commonName, password) != null
  290.                        return GetDirectoryEntry(commonName, password); 
  291.                    else 
  292.                        return null
  293.               } 
  294.               else 
  295.               { 
  296.                    return null
  297.               } 
  298.          } 
  299.   
  300.          /// 
  301.          ///根据组名取得用户组的 对象 
  302.          /// 
  303.          /// 组名 
  304.          /// 
  305.          public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName) 
  306.          { 
  307.               DirectoryEntry de = GetDirectoryObject(); 
  308.               DirectorySearcher deSearch = new DirectorySearcher(de); 
  309.               deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))"
  310.               deSearch.SearchScope = SearchScope.Subtree; 
  311.   
  312.               try 
  313.               { 
  314.                    SearchResult result = deSearch.FindOne(); 
  315.                    de = new DirectoryEntry(result.Path); 
  316.                    return de; 
  317.               } 
  318.               catch 
  319.               { 
  320.                    return null
  321.               } 
  322.          } 
  323.          #endregion 
  324.          #region GetProperty 
  325.   
  326.          /// 
  327.          ///获得指定 指定属性名对应的值 
  328.          /// 
  329.          ///  
  330.          /// 属性名称 
  331.          ///属性值 
  332.          public static string GetProperty(DirectoryEntry de, string propertyName) 
  333.          { 
  334.               if(de.Properties.Contains(propertyName)) 
  335.               { 
  336.                    return de.Properties[propertyName][0].ToString() ; 
  337.               } 
  338.               else 
  339.               { 
  340.                    return string.Empty; 
  341.               } 
  342.          } 
  343.   
  344.          /// 
  345.          ///获得指定搜索结果 中指定属性名对应的值 
  346.          /// 
  347.          ///  
  348.          /// 属性名称 
  349.          ///属性值 
  350.          public static string GetProperty(SearchResult searchResult, string propertyName) 
  351.          { 
  352.               if(searchResult.Properties.Contains(propertyName)) 
  353.               { 
  354.                    return searchResult.Properties[propertyName][0].ToString() ; 
  355.               } 
  356.               else 
  357.               { 
  358.                    return string.Empty; 
  359.               } 
  360.          } 
  361.          #endregion 
  362.   
  363.          /// 
  364.          ///设置指定 的属性值 
  365.          /// 
  366.          ///  
  367.          /// 属性名称 
  368.          /// 属性值 
  369.          public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue) 
  370.          { 
  371.               if(propertyValue != string.Empty || propertyValue != "" || propertyValue != null
  372.               { 
  373.                    if(de.Properties.Contains(propertyName)) 
  374.                    { 
  375.                        de.Properties[propertyName][0] = propertyValue;  
  376.                    } 
  377.                    else 
  378.                    { 
  379.                        de.Properties[propertyName].Add(propertyValue); 
  380.                    } 
  381.               } 
  382.          } 
  383.   
  384.          /// 
  385.          ///创建新的用户 
  386.          /// 
  387.          /// DN 位置。例如:OU=共享平台 或 CN=Users 
  388.          /// 公共名称 
  389.          /// 帐号 
  390.          /// 密码 
  391.          /// 
  392.          public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password) 
  393.          { 
  394.               DirectoryEntry entry = GetDirectoryObject(); 
  395.               DirectoryEntry subEntry = entry.Children.Find(ldapDN); 
  396.               DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user"); 
  397.               deUser.Properties["sAMAccountName"].Value = sAMAccountName; 
  398.               deUser.CommitChanges(); 
  399.               ADHelper.EnableUser(commonName); 
  400.               ADHelper.SetPassword(commonName, password); 
  401.               deUser.Close(); 
  402.               return deUser; 
  403.          } 
  404.   
  405.          /// 
  406.          ///创建新的用户。默认创建在 Users 单元下。 
  407.          /// 
  408.          /// 公共名称 
  409.          /// 帐号 
  410.          /// 密码 
  411.          /// 
  412.          public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password) 
  413.          { 
  414.               return CreateNewUser("CN=Users", commonName, sAMAccountName, password); 
  415.          } 
  416.   
  417.          /// 
  418.          ///判断指定公共名称的用户是否存在 
  419.          /// 
  420.          /// 用户公共名称 
  421.          ///如果存在,返回 true;否则返回 false 
  422.          public static bool IsUserExists(string commonName) 
  423.          { 
  424.               DirectoryEntry de = GetDirectoryObject(); 
  425.               DirectorySearcher deSearch = new DirectorySearcher(de); 
  426.               deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";       // LDAP 查询串 
  427.               SearchResultCollection results = deSearch.FindAll(); 
  428.   
  429.               if (results.Count == 0) 
  430.                    return false
  431.               else 
  432.                    return true
  433.          } 
  434.   
  435.          /// 
  436.          ///判断用户帐号是否激活 
  437.          /// 
  438.          /// 用户帐号属性控制器 
  439.          ///如果用户帐号已经激活,返回 true;否则返回 false 
  440.          public static bool IsAccountActive(int userAccountControl) 
  441.          { 
  442.               int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE); 
  443.               int flagExists = userAccountControl & userAccountControl_Disabled; 
  444.   
  445.               if (flagExists > 0) 
  446.                    return false
  447.               else 
  448.                    return true
  449.          } 
  450.   
  451.          /// 
  452.          ///判断用户与密码是否足够以满足身份验证进而登录 
  453.          /// 
  454.          /// 用户公共名称 
  455.          /// 密码 
  456.          ///如能可正常登录,则返回 true;否则返回 false 
  457.          public static LoginResult Login(string commonName, string password) 
  458.          { 
  459.               DirectoryEntry de = GetDirectoryEntry(commonName); 
  460.   
  461.               if (de != null
  462.               { 
  463.                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。 
  464.                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]); 
  465.                    de.Close(); 
  466.   
  467.                    if (!IsAccountActive(userAccountControl)) 
  468.                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE; 
  469.   
  470.                    if (GetDirectoryEntry(commonName, password) != null
  471.                        return LoginResult.LOGIN_USER_OK; 
  472.                    else 
  473.                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT; 
  474.               } 
  475.               else 
  476.               { 
  477.                    return LoginResult.LOGIN_USER_DOESNT_EXIST;  
  478.               } 
  479.          } 
  480.   
  481.          /// 
  482.          ///判断用户帐号与密码是否足够以满足身份验证进而登录 
  483.          /// 
  484.          /// 用户帐号 
  485.          /// 密码 
  486.          ///如能可正常登录,则返回 true;否则返回 false 
  487.          public static LoginResult LoginByAccount(string sAMAccountName, string password) 
  488.          { 
  489.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName); 
  490.                     
  491.               if (de != null
  492.               { 
  493.                    // 必须在判断用户密码正确前,对帐号激活属性进行判断;否则将出现异常。 
  494.                    int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]); 
  495.                    de.Close(); 
  496.   
  497.                    if (!IsAccountActive(userAccountControl)) 
  498.                        return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE; 
  499.   
  500.                    if (GetDirectoryEntryByAccount(sAMAccountName, password) != null
  501.                        return LoginResult.LOGIN_USER_OK; 
  502.                    else 
  503.                        return LoginResult.LOGIN_USER_PASSWORD_INCORRECT; 
  504.               } 
  505.               else 
  506.               { 
  507.                    return LoginResult.LOGIN_USER_DOESNT_EXIST;  
  508.               } 
  509.          } 
  510.   
  511.          /// 
  512.          ///设置用户密码,管理员可以通过它来修改指定用户的密码。 
  513.          /// 
  514.          /// 用户公共名称 
  515.          /// 用户新密码 
  516.          public static void SetPassword(string commonName, string newPassword) 
  517.          { 
  518.               DirectoryEntry de = GetDirectoryEntry(commonName); 
  519.                
  520.               // 模拟超级管理员,以达到有权限修改用户密码 
  521.               impersonate.BeginImpersonate(); 
  522.               de.Invoke("SetPassword", new object[]{newPassword}); 
  523.               impersonate.StopImpersonate(); 
  524.   
  525.               de.Close(); 
  526.          } 
  527.   
  528.          /// 
  529.          ///设置帐号密码,管理员可以通过它来修改指定帐号的密码。 
  530.          /// 
  531.          /// 用户帐号 
  532.          /// 用户新密码 
  533.          public static void SetPasswordByAccount(string sAMAccountName, string newPassword) 
  534.          { 
  535.               DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName); 
  536.   
  537.               // 模拟超级管理员,以达到有权限修改用户密码 
  538.               IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName); 
  539.               impersonate.BeginImpersonate(); 
  540.               de.Invoke("SetPassword", new object[]{newPassword}); 
  541.               impersonate.StopImpersonate(); 
  542.   
  543.               de.Close(); 
  544.          } 
  545.   
  546.          /// 
  547.          ///修改用户密码 
  548.          /// 
  549.          /// 用户公共名称 
  550.          /// 旧密码 
  551.          /// 新密码 
  552.          public static void ChangeUserPassword (string commonName, string oldPassword, string newPassword) 
  553.          { 
  554.               // to-do: 需要解决密码策略问题 
  555.               DirectoryEntry oUser = GetDirectoryEntry(commonName); 
  556.               oUser.Invoke("ChangePassword", new Object[]{oldPassword, newPassword}); 
  557.               oUser.Close(); 
  558.          } 
  559.   
  560.          /// 
  561.          ///启用指定公共名称的用户 
  562.          /// 
  563.          /// 用户公共名称 
  564.          public static void EnableUser(string commonName) 
  565.          { 
  566.               EnableUser(GetDirectoryEntry(commonName)); 
  567.          } 
  568.   
  569.          /// 
  570.          ///启用指定 的用户 
  571.          /// 
  572.          ///  
  573.          public static void EnableUser(DirectoryEntry de) 
  574.          { 
  575.               impersonate.BeginImpersonate(); 
  576.               de.Properties["userAccountControl"][0] = ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADHelper.ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD; 
  577.               de.CommitChanges(); 
  578.               impersonate.StopImpersonate(); 
  579.               de.Close(); 
  580.          } 
  581.   
  582.          /// 
  583.          ///禁用指定公共名称的用户 
  584.          /// 
  585.          /// 用户公共名称 
  586.          public static void DisableUser(string commonName) 
  587.          { 
  588.               DisableUser(GetDirectoryEntry(commonName)); 
  589.          } 
  590.   
  591.          /// 
  592.          ///禁用指定 的用户 
  593.          /// 
  594.          ///  
  595.          public static void DisableUser(DirectoryEntry de) 
  596.          { 
  597.               impersonate.BeginImpersonate(); 
  598.               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; 
  599.               de.CommitChanges(); 
  600.               impersonate.StopImpersonate(); 
  601.               de.Close(); 
  602.          } 
  603.   
  604.          /// 
  605.          ///将指定的用户添加到指定的组中。默认为 Users 下的组和用户。 
  606.          /// 
  607.          /// 用户公共名称 
  608.          /// 组名 
  609.          public static void AddUserToGroup(string userCommonName, string groupName) 
  610.           { 
  611.               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName); 
  612.               DirectoryEntry oUser = GetDirectoryEntry(userCommonName); 
  613.                
  614.               impersonate.BeginImpersonate(); 
  615.               oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value); 
  616.               oGroup.CommitChanges(); 
  617.               impersonate.StopImpersonate(); 
  618.   
  619.               oGroup.Close(); 
  620.               oUser.Close(); 
  621.          } 
  622.   
  623.          /// 
  624.          ///将用户从指定组中移除。默认为 Users 下的组和用户。 
  625.          /// 
  626.          /// 用户公共名称 
  627.          /// 组名 
  628.          public static void RemoveUserFromGroup(string userCommonName, string groupName) 
  629.          { 
  630.               DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName); 
  631.               DirectoryEntry oUser = GetDirectoryEntry(userCommonName); 
  632.                
  633.               impersonate.BeginImpersonate(); 
  634.               oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value); 
  635.               oGroup.CommitChanges(); 
  636.               impersonate.StopImpersonate(); 
  637.   
  638.               oGroup.Close(); 
  639.               oUser.Close(); 
  640.          } 
  641.   
  642.      } 
  643.   
  644.      /// 
  645.      ///用户模拟角色类。实现在程序段内进行用户角色模拟。 
  646.      /// 
  647.      public class IdentityImpersonation 
  648.      { 
  649.          [DllImport("advapi32.dll", SetLastError=true)] 
  650.          public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); 
  651.   
  652.          [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
  653.          public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); 
  654.   
  655.          [DllImport("kernel32.dll", CharSet=CharSet.Auto)] 
  656.          public extern static bool CloseHandle(IntPtr handle); 
  657.   
  658.          // 要模拟的用户的用户名、密码、域(机器名) 
  659.          private String _sImperUsername; 
  660.          private String _sImperPassword; 
  661.          private String _sImperDomain; 
  662.          // 记录模拟上下文 
  663.          private WindowsImpersonationContext _imperContext; 
  664.          private IntPtr _adminToken; 
  665.          private IntPtr _dupeToken; 
  666.          // 是否已停止模拟 
  667.          private Boolean _bClosed; 
  668.   
  669.          /// 
  670.          ///构造函数 
  671.          /// 
  672.          /// 所要模拟的用户的用户名 
  673.          /// 所要模拟的用户的密码 
  674.          /// 所要模拟的用户所在的域 
  675.          public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)  
  676.          { 
  677.               _sImperUsername = impersonationUsername; 
  678.               _sImperPassword = impersonationPassword; 
  679.               _sImperDomain = impersonationDomain; 
  680.   
  681.               _adminToken = IntPtr.Zero; 
  682.               _dupeToken = IntPtr.Zero; 
  683.               _bClosed = true
  684.          } 
  685.   
  686.          /// 
  687.          ///析构函数 
  688.          /// 
  689.          ~IdentityImpersonation()  
  690.          { 
  691.               if(!_bClosed)  
  692.               { 
  693.                    StopImpersonate(); 
  694.               } 
  695.          } 
  696.   
  697.          /// 
  698.          ///开始身份角色模拟。 
  699.          /// 
  700.          /// 
  701.          public Boolean BeginImpersonate()  
  702.          { 
  703.               Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken); 
  704.                          
  705.               if(!bLogined)  
  706.               { 
  707.                    return false
  708.               } 
  709.   
  710.               Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken); 
  711.   
  712.               if(!bDuped)  
  713.               { 
  714.                    return false
  715.               } 
  716.   
  717.               WindowsIdentity fakeId = new WindowsIdentity(_dupeToken); 
  718.               _imperContext = fakeId.Impersonate(); 
  719.   
  720.               _bClosed = false
  721.   
  722.               return true
  723.          } 
  724.   
  725.          /// 
  726.          ///停止身分角色模拟。 
  727.          /// 
  728.          public void StopImpersonate()  
  729.          { 
  730.               _imperContext.Undo(); 
  731.               CloseHandle(_dupeToken); 
  732.               CloseHandle(_adminToken); 
  733.               _bClosed = true
  734.          } 
  735.      } 
  736.   
  737. 简单的应用 
  738. [WebMethod] 
  739.   public string IsAuthenticated(string UserID,string Password) 
  740.   { 
  741.             string _path = "LDAP://" + adm + "/DC=lamda,DC=com,DC=cn";//"LDAP://172.75.200.1/DC=名字,DC=com,DC=cn"
  742.    string _filterAttribute=null
  743.    
  744.    DirectoryEntry entry = new DirectoryEntry(_path,UserID,Password); 
  745.     
  746.    try 
  747.    { 
  748.     //Bind to the native AdsObject to force authentication. 
  749.     DirectorySearcher search = new DirectorySearcher(entry); 
  750.     search.Filter = "(SAMAccountName=" + UserID + ")"
  751.     SearchResult result = search.FindOne(); 
  752.      
  753.     if(null == result) 
  754.     { 
  755.      _filterAttribute="登录失败: 未知的用户名或错误密码."
  756.     } 
  757.     else 
  758.     { 
  759.      _filterAttribute="true"
  760.     } 
  761.     
  762.    } 
  763.    catch (Exception ex) 
  764.    { 
  765.  
  766.  
  767.      return ex.Message; 
  768.    } 
  769.    return _filterAttribute; 
  770.   } 
  771.   [WebMethod] 
  772.   public string[] LDAPMessage(string UserID) 
  773.   { 
  774.    string _path = "LDAP://"+adm+"/DC=it2004,DC=名字,DC=com,DC=cn"
  775.    string[] _filterAttribute=new string[5]; 
  776.    string[] msg = {"samaccountname","displayname","department","company"}; 
  777.    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813"); 
  778.     
  779.    try 
  780.    {  
  781.  
  782.     Object obj = entry.NativeObject; 
  783.      
  784.     DirectorySearcher search = new DirectorySearcher(entry); 
  785.     search.Filter = "(SAMAccountName=" + UserID + ")"
  786.     SearchResult result = search.FindOne(); 
  787.      
  788.     if(null == result) 
  789.     { 
  790.      _filterAttribute[0]="登录失败: 未知的用户名或错误密码."
  791.     } 
  792.     else 
  793.     { 
  794.      _filterAttribute[0]="true";   
  795.      for(int propertyCounter = 1; propertyCounter < 5; propertyCounter++) 
  796.      { 
  797.         
  798.       if(propertyCounter==4 &&  result.Properties[msg[propertyCounter-1]][0]==null
  799.        break
  800.       _filterAttribute[propertyCounter]=result.Properties[msg[propertyCounter-1]][0].ToString(); 
  801.        
  802.      } 
  803.     } 
  804.     
  805.    } 
  806.    catch (Exception ex) 
  807.    { 
  808.     //_filterAttribute[0]=ex.Message; 
  809.    } 
  810.    return _filterAttribute; 
  811.   } 
  812.   [WebMethod] 
  813.   public string[] AllMembers()  
  814.   { 
  815.     
  816.    string[] msg; 
  817.    string _path = "LDAP://名字"
  818.    DirectoryEntry entry = new DirectoryEntry(_path,"180037","790813"); 
  819.     
  820.   
  821.    //Bind to the native AdsObject to force authentication. 
  822.    Object obj = entry.NativeObject; 
  823.    System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry); 
  824.    mySearcher.Filter = "(SAMAccountName=180037)"
  825.    msg=new string[mySearcher.FindAll().Count]; 
  826.    int i=0; 
  827.    foreach(System.DirectoryServices.SearchResult result in mySearcher.FindAll())  
  828.    { 
  829.     msg[i++]=result.Path; 
  830.    } 
  831.    return msg; 
  832.   } 
  833.   
  834.   

 

posted on 2012-10-09 09:00  王玉涛  阅读(477)  评论(0编辑  收藏  举报