【问题标题】:The Spring Boot way to do LDAP authenticationSpring Boot 进行 LDAP 身份验证的方式
【发布时间】:2020-08-07 19:15:00
【问题描述】:

我有以下可以使用 LDAP 对用户进行身份验证的工作代码。如您所见,它非常简单。但是我怎样才能以 Spring Boot 的方式做同样的事情呢?

     try {
            Hashtable<String, Object> env = new Hashtable<>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, “ldaps://xxxxxxxx.abcgroup.xyz.com:636”);
            env.put(Context.SECURITY_AUTHENTICATION, "simple"); // fixed value
            env.put(Context.SECURITY_PRINCIPAL, “myid@abcgroup.xyz.com”);
            env.put(Context.SECURITY_CREDENTIALS, "mypassword");
            new InitialDirContext(env);
           // authentication successful.
      } catch (Exception exception) {
           // authentication failed.
      }

【问题讨论】:

    标签: spring-boot spring-security ldap spring-ldap spring-security-ldap


    【解决方案1】:

    首先你应该将你的连接信息写入一个配置文件,例如一个 ldap.yml 文件。

    ldap:
      url: ldap://XXXXXXX:389/
      root: cn=root,dc=root,dc=com
      userDn: cn=root,dc=root,dc=com
      password: XXXXXX
      baseDN: dc=root,dc=com
      clean: true
      pooled: false
    

    然后使用这些属性注入一个ldaptemplate bean,这是一个propeties类:

    @ConfigurationProperties(prefix = "ldap")
    public class LdapProperties {
    private String url;
    private String userDn;
    private String password;
    private String baseDN;
    private String clean;
    private String root;
    private boolean pooled = false;
    }
    

    这是一个配置类:

    @Configuration
    @EnableConfigurationProperties({LdapProperties.class})
    public class LdapConfiguration {
    @Autowired
    LdapProperties ldapProperties;
    @Bean
    public LdapTemplate ldapTemplate() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl(ldapProperties.getUrl());
        contextSource.setUserDn(ldapProperties.getUserDn());
        contextSource.setPassword(ldapProperties.getPassword());
        contextSource.setPooled(ldapProperties.getPooled());
        contextSource.setBase(ldapProperties.getBaseDN());
        contextSource.afterPropertiesSet();
        return new LdapTemplate(contextSource);
       }
       }
    

    然后您可以使用@Autowired Annotations。此注解允许 Spring 解析协作 bean 并将其注入到您的 bean 中。

        @Autowired
        LdapTemplate ldapTemplate;
    

    使用 ldapTemplate,您可以像关系数据库一样进行 CRUD。当然,您也可以进行身份​​验证。 这是我第一次在stackoverflow回答问题,欢迎大家指出我的错误。

    【讨论】:

    • 您好,抱歉回复晚了!其实我已经想出了如何解决我的问题。我的解决方案与您的不同。
    • 如果可以的话可以分享一下你的解决方案吗?我也是ldap的初学者,有问题可以交流一下。
    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2020-07-06
    • 2022-01-20
    • 2017-07-30
    • 2018-03-11
    • 2011-02-01
    相关资源
    最近更新 更多