spring-ldap NameNotFoundException 没有这样的对象

spring-ldap NameNotFoundException no such object

我在使用 spring-ldap 时遇到此异常:

服务器未知异常:[LDAP: error code 32 - No Such Object]; 
nested exception is javax.naming.NameNotFoundException: 
[LDAP: error code 32 - No Such Object]; remaining name 'uid=lyh,ou=Users,dc=xinsight,dc=com'

1.my配置

<bean id="ldapTemplate"  class="org.springframework.ldap.core.LdapTemplate">
    <constructor-arg ref="contextSource"/>
</bean>

<bean id="contextSource"
      class="org.springframework.ldap.core.support.LdapContextSource">
    <property name="url" value="ldap://168.2.8.77:389" />
    <property name="base" value="dc=xinsight,dc=com" />
    <property name="userDn" value="cn=Manager,dc=xinsight,dc=com" />
    <property name="password" value="psw" />
    <!--<property name="referral" value="follow"/>-->
</bean>

2.my代码

public void create() {
    User user = new User();
    user.setFdUsername("lyhtest");
    user.setFdTenantName("root");
    user.setFdLdapPassword("ldappsw");
    user.setFdUserid(Long.valueOf(10));

    Name dn = buildDn(user);
    ldapTemplate.bind(dn, null, buildAttributes(user));
}

/**
 * 动态创建DN
 * spring-ldap提供了:LdapNameBuilder,LdapUtils
 */
private Name buildDn(User user) {
    return LdapNameBuilder.newInstance(BASE_DN)
            .add("ou", "Users")
            .build();
}

/**
 * 配置属性
 * @param user
 * @return
 */
private Attributes buildAttributes(User user) {
    Attributes attrs = new BasicAttributes();

    BasicAttribute objectclass = new BasicAttribute("objectclass");
    objectclass.add("top");
    objectclass.add("posixAccount");
    objectclass.add("inetOrgPerson");
    attrs.put(objectclass);

    attrs.put("userPassword", user.getFdLdapPassword());
    attrs.put("cn",user.getFdUsername()+"@"+user.getFdTenantName());
    attrs.put("sn",user.getFdUsername()+"@"+user.getFdTenantName());
    attrs.put("displayName",user.getFdUsername()+"@"+user.getFdTenantName());
    attrs.put("homeDirectory","/root");
    attrs.put("uidNumber",user.getFdUserid().toString());
    attrs.put("uid",user.getFdUsername());
    attrs.put("gidNumber","0");

    return attrs;
}

3.ldap 管理员 ldap admin

4.I也写了查询方法,我可以从ldap中获取用户信息。所以连接没问题。

感谢您的帮助!

我已经解决了这个问题。

1.I 检查了 ldap admin 的日志文件,我看到了 "dn":

ou=Users,dc=xinsight,dc=com,dc=xinsight,dc=com

2.before 之后

return LdapNameBuilder.newInstance(Base_DN)
            .add("ou", "Users")
            .add("uid","lyh3")
            .build();

return LdapNameBuilder.newInstance()
            .add("ou", "Users")
            .add("uid","lyh3")
            .build();

删除参数Base_DN后,我成功创建了一个用户。然后我查看ldap admin的日志文件,它显示:

dn: ou=Users,dc=xinsight,dc=com

虽然不知道为什么dn的值有重复'dc=xinsight,dc=com'。我是从官方文档spring-ldap official doc上复制过来的,在构建'dn'时显示需要一个'base_dn':

protected Name buildDn(Person p) {
  return LdapNameBuilder.newInstance(BASE_DN)
    .add("c", p.getCountry())
    .add("ou", p.getCompany())
    .add("cn", p.getFullname())
    .build();
}