【问题标题】:How can I change my LDAP configs to Spring Security realization?如何将我的 LDAP 配置更改为 Spring Security 实现?
【发布时间】:2025-12-30 02:40:11
【问题描述】:

我有这个 LDAP 配置:

Hashtable env = new Hashtable();

            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, "ldap://.....");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, "login);
            env.put(Context.SECURITY_CREDENTIALS, password);

            // Create the initial context 
            DirContext ctx = new InitialDirContext(env);
            boolean result = ctx != null;

如何更改此配置以实现 Spring Security?

auth.ldapAuthentication().....

【问题讨论】:

    标签: spring-security ldap


    【解决方案1】:

    您可以将此示例代码用作模板。在我的例子中,LDAP 提供程序 URL 是 ldap://localhost:1389/dc=example,dc=com,并且用户条目具有以下 DN 模式:uid={0},ou=people,dc=example,dc=com。这意味着uid 属性将用作用户名。

    LdapContextSource ctxSrc = new LdapContextSource();
    ctxSrc.setUrl("ldap://localhost:1389");
    ctxSrc.setBase("dc=example,dc=com");
    ctxSrc.setUserDn("login");
    ctxSrc.setPassword("password");
    ctxSrc.afterPropertiesSet();
    
    auth
      .ldapAuthentication()
      .contextSource(ctxSrc)
      .userSearchBase("ou=people")
      .userSearchFilter("(uid={0})");
    

    【讨论】: