You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring LDAP出现LdapName转String类型转换异常求助

Spring LDAP类型转换异常(LdapName无法转为String)解决方法

问题根源

你遇到的class javax.naming.ldap.LdapName cannot be cast to class java.lang.String异常,是因为ldapAttributes.getName()返回的是javax.naming.ldap.LdapName类型的条目DN对象,而非String类型的属性值,代码中直接将其作为String参数传递,触发了类型转换错误。

代码修正方案

根据业务需求,有两种修正方向:

方向1:若确实需要使用DN字符串

将所有ldapAttributes.getName()替换为ldapAttributes.getName().toString(),把LdapName对象转为String类型:

private void createUser(LdapAttributes ldapAttributes) {
    String dnString = ldapAttributes.getName().toString();

    LdapName dn = LdapNameBuilder
            .newInstance()
            .add("ou", "users")
            .add("cn", dnString)
            .build();

    DirContextAdapter context = new DirContextAdapter(dn);

    context.setAttributeValues(
            "objectclass",
            new String[]
                    { "top",
                      "person",
                      "organizationalPerson",
                      "inetOrgPerson" });
    context.setAttributeValue("cn", dnString);
    context.setAttributeValue("sn", dnString);
    context.setAttributeValue("userPassword", ldapAttributes.get("userPassword").get());

    ldapTemplate.bind(context);
}

方向2:若实际需要的是用户CN属性值

从LdapAttributes中直接获取CN属性的String值(这更符合创建用户的业务逻辑):

private void createUser(LdapAttributes ldapAttributes) {
    // 从属性集中获取CN值
    String cnValue = ldapAttributes.getString("cn");
    // 若getString方法不可用,可改用:
    // String cnValue = (String) ldapAttributes.get("cn").get();

    LdapName dn = LdapNameBuilder
            .newInstance()
            .add("ou", "users")
            .add("cn", cnValue)
            .build();

    DirContextAdapter context = new DirContextAdapter(dn);

    context.setAttributeValues(
            "objectclass",
            new String[]
                    { "top",
                      "person",
                      "organizationalPerson",
                      "inetOrgPerson" });
    context.setAttributeValue("cn", cnValue);
    // 建议从属性集中获取对应的姓氏值,而非复用CN
    String snValue = ldapAttributes.getString("sn");
    context.setAttributeValue("sn", snValue);
    context.setAttributeValue("userPassword", ldapAttributes.get("userPassword").get());

    ldapTemplate.bind(context);
}

额外说明

  • 代码中sn字段直接复用CN值不符合LDAP规范,建议从传入的LdapAttributes中获取对应的姓氏属性值。
  • 你的Spring LDAP版本(2.4.1)和Spring Boot版本(2.7.12)兼容,无需调整版本。

内容的提问来源于stack exchange,提问作者Mathieu Thauvoye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 07:25:22