简体   繁体   English

Java使用Apache Directory的LDAP API调用Active Directory

[英]Java calling Active Directory using Apache Directory's LDAP API

I'm trying to connect to an Active Directory from Activiti, using Apache Directory's LDAP API. 我正在尝试使用Apache Directory的LDAP API从Activiti连接到Active Directory。 I think I've managed to authenticate my user, but subsequent queries for users finds nothing. 我认为我已经成功验证了我的用户身份,但是随后对用户的查询却什么也没找到。

Here's my Java code: 这是我的Java代码:

package com.abc.activiti.ldap;

import org.activiti.engine.ActivitiException;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.UserQueryImpl;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.activiti.engine.impl.persistence.entity.UserManager;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.exception.LdapException;
import org.apache.directory.ldap.client.api.message.BindResponse;
import org.apache.directory.ldap.client.api.message.SearchResponse;
import org.apache.directory.ldap.client.api.message.SearchResultEntry;
import org.apache.directory.shared.ldap.cursor.Cursor;
import org.apache.directory.shared.ldap.entry.EntryAttribute;
import org.apache.directory.shared.ldap.filter.SearchScope;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
import org.apache.mina.core.session.IoSession;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class LDAPUserManager extends UserManager {
    private final static Logger logger = LoggerFactory.getLogger(LDAPUserManager.class);

    private LDAPConnectionParams ldapConnectionParams;

    public LDAPUserManager(LDAPConnectionParams ldapConnectionParams) {
        this.ldapConnectionParams = ldapConnectionParams;
    }

    public Boolean checkPassword(String userId, String password) {
        Boolean result;
        LdapConnection connection;

        String userDN = ldapConnectionParams.getUserPrefix() + "=" +
                userId + "," + ldapConnectionParams.getUserGroup();
        logger.debug("Checking password, using connection string: '" + userDN + "'");
        try {
            connection = openConnection();
            BindResponse bindResponse = connection.bind(userDN, password);
            result = bindResponse.getLdapResult().getResultCode() == ResultCodeEnum.SUCCESS;
        } catch (LdapException e) {
            throw new ActivitiException("LDAP exception while binding", e);
        } catch (IOException e) {
            throw new ActivitiException("IO exception while binding", e);
        }
        // TODO: move this into a finally clause above
        closeConnection(connection);

        return result;
    }

    public List<User> findUserByQueryCriteria(Object o, Page page) {
        List<User> result = new ArrayList<User>();

        UserQueryImpl userQuery = (UserQueryImpl)o;
        StringBuilder queryString = new StringBuilder();
        queryString.append("(").append(ldapConnectionParams.getUserPrefix()).append("=")
                .append(userQuery.getId()).append(")");

        logger.debug("Looking for users: '" + queryString + "'");
        LdapConnection connection;

        try {
            connection = openConnection();
            Cursor<SearchResponse> responseCursor = connection.search(
                    ldapConnectionParams.getUserGroup(), queryString.toString(),
                    SearchScope.ONELEVEL,
                    "cn", "sAMAccountName", "sn");

            logger.debug("Got cursor: " + responseCursor);

            for (SearchResponse response : responseCursor) {
                logger.debug("It's a rsponse: " + response);
            }

            int maxUsers = 10;
            while (responseCursor.next() && maxUsers-- > 0) {
                User user = new UserEntity();
                SearchResultEntry searchResponse = (SearchResultEntry)responseCursor.get();
                logger.debug("Got item: " + searchResponse);
                result.add(user);
            }
            responseCursor.close();
        } catch (LdapException e) {
            throw new ActivitiException("While searching for user in LDAP", e);
        } catch (Exception e) {
            throw new ActivitiException("While searching for user in LDAP", e);
        }
        // TODO: move this into a finally clause above
        closeConnection(connection);
        logger.debug("Returning users: " + result);
        return result;
    }

    private void closeConnection(LdapConnection connection) {
        try {
            connection.unBind();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private LdapConnection openConnection() throws LdapException, IOException {
        LdapConnection connection = new LdapConnection(
                ldapConnectionParams.getLdapServer(),
                ldapConnectionParams.getLdapPort()) {

            public void exceptionCaught(IoSession ioSession, Throwable throwable) throws Exception {
                logger.error("Exception thrown in " + ioSession, throwable);
            }
        };
        connection.connect();
        return connection;
    }

}

I read some stuff from spring bean definitions: 我从Spring bean定义中读到了一些东西:

<property name="ldapServer" value="secret"/>
<property name="ldapPort" value="389"/>
<property name="ldapUser" value="CN=Stefan Blixt,OU=x,OU=x,OU=x,DC=x,DC=x"/>
<property name="ldapPassword" value="secret"/>
<property name="userGroup" value="OU=x,OU=x,OU=x,DC=x,DC=x"/>
<property name="userPrefix" value="CN"/>

Activiti will first run checkPassword(), which returns true, then it will run findUserByQueryCriteria(), which outputs this: Activiti将首先运行checkPassword(),该方法返回true,然后它将运行findUserByQueryCriteria(),该输出如下:

DEBUG: com.abc.activiti.ldap.LDAPUserManager - Looking for users: '(CN=Stefan Blixt)'
DEBUG: com.abc.activiti.ldap.LDAPUserManager - Got cursor: org.apache.directory.ldap.client.api.SearchCursor@1e3940a
DEBUG: com.abc.activiti.ldap.LDAPUserManager - Returning users: []

I have managed to connect and do this kind of query in Apache Directory Studio: 我已经设法连接并在Apache Directory Studio中执行以下查询:

Active Directory Studio搜索快照

That one will give me a result with the entry for Stefan Blixt. 那会给我带来Stefan Blixt参赛作品的结果。

I've edited some paths above for privacy. 为了保护隐私,我已经编辑了一些路径。

Any ideas? 有任何想法吗? Are there any classic culprits that may result in zero results when doing an LDAP user search? 进行LDAP用户搜索时,是否有可能导致零结果的经典元凶? I've tried using uid, sAMAccountName etc when searching - always the same result. 我尝试在搜索时使用uid,sAMAccountName等-总是相同的结果。

It appears that findUserByQueryCriteria is creating a new LdapConnection and not doing a bind() on it. 看来findUserByQueryCriteria正在创建一个新的LdapConnection,并且没有对其执行bind() Perhaps your AD server does not allow anonymous queries. 也许您的AD服务器不允许匿名查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Apache LDAP API 在下次登录 Active Directory 时强制更改密码 - Force password change on next login with Active Directory using Apache LDAP API 使用LDAP,Java Play Framework通过Active Directory进行身份验证 - Authenticate via Active Directory using LDAP, Java Play Framework 使用LDAP从Active Directory检索用户属性-JAVA - Retrieving user attributes from Active Directory using LDAP - JAVA 使用LDAP WITHOUT servername从Java(Linux)到Active Directory进行身份验证 - Authenticating from Java (Linux) to Active Directory using LDAP WITHOUT servername JAVA-活动目录和ldap密码属性 - JAVA - Active directory and ldap password properties LDAP单点登录,用于Java中的Active Directory查询 - LDAP Single Sign On for Active Directory queries in Java 使用LDAP / Java启用Active Directory用户 - Enable an Active Directory user with LDAP/Java 无法使用 LDAP 连接从 Java 后端检索 Active Directory 用户 [LDAP:错误代码 32 – 无此类对象] - Unable to retrieve Active Directory users from Java backend using LDAP connection [LDAP: error code 32 – No Such Object] 我在骆驼下使用apache shiro,无法将组映射到具有ldap / active目录的角色 - I am using apache shiro under camel and I cannot map groups to roles with ldap/active directory Java cmd 的活动目录 - Java cmd's active directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM