2011-02-28 93 views
3

我们有一个网站,可以作为员工和互联网的外部人员使用的Intranet。我们所有的员工账号都在Active Directory中。因此,当内部员工浏览URL(例如http://app.abc.com)时,他们应该使用他们的AD帐户自动登录。用c#ASP.Net中的Active Directory帐户自动登录网站

但是,对于外部用户,他们必须使用他们的用户名和密码。只需查找数据库并进行身份验证,我就可以轻松完成这部分任务。

我想知道如何自动登录AD用户进入网站。

回答

0
public bool Authenticate(string userName, string passwd) 
     { 
      //Domain . 
      string domain = "YOUR_DOMAIN_NAME"; 
      string domainAndUsername = domain + @"\" + userName; 
      DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, passwd); 

      try 
      { 
       //Bind to the native AdsObject to force authentication. 
       object obj = entry.NativeObject; 

       DirectorySearcher search = new DirectorySearcher(entry); 

       search.Filter = "(SAMAccountName=" + userName + ")"; 
       search.PropertiesToLoad.Add("cn"); 
       SearchResult result = search.FindOne(); 

       if (null == result) 
       { 
        return false; 
       } 

       //Update the new path to the user in the directory. 
       _path = result.Path; 
       _filterAttribute = (string)result.Properties["cn"][0]; 
      } 
      catch (Exception ex) 
      { 

       PageLogger.AddToLogError("AUTH_ERROR", ex); 
       return false; 

      } 

      return true; 
     } 

     private string GetGroups() 
     { 
      DirectorySearcher search = new DirectorySearcher(_path); 
      search.Filter = "(cn=" + _filterAttribute + ")"; 
      search.PropertiesToLoad.Add("memberOf"); 
      StringBuilder groupNames = new StringBuilder(); 

      try 
      { 
       SearchResult result = search.FindOne(); 
       int propertyCount = result.Properties["memberOf"].Count; 
       string dn; 
       int equalsIndex, commaIndex; 

       for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) 
       { 
        dn = (string)result.Properties["memberOf"][propertyCounter]; 
        equalsIndex = dn.IndexOf("=", 1); 
        commaIndex = dn.IndexOf(",", 1); 
        if (-1 == equalsIndex) 
        { 
         return null; 
        } 
        groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); 
        groupNames.Append("|"); 
       } 
      } 
      catch (Exception ex) 
      { 
       throw new Exception("Error obtaining group names. " + ex.Message); 
      } 
      return groupNames.ToString(); 
     }