c# LDAP 验证

using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;

namespace FormsAuth
{
  public class LdapAuthentication
  {
    private string _path;
    private string _filterAttribute;

    public LdapAuthentication(string path)
    {
      _path = path;
    }

    public bool IsAuthenticated(string domain, string username, string pwd)
    {
      string domainAndUsername = domain + @"\" + username;
      DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

      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)
      {
        throw new Exception("Error authenticating user. " + ex.Message);
      }

      return true;
    }

    public 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();
  }
}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值