首页 > 解决方案 > Spring Boot LDAP 身份验证:在身份验证时获取用户数据

问题描述

我开发了一个 Spring Boot 应用程序,我想使用 LDAP 服务器执行身份验证。在生产中它将是一个 Active Directory 服务器,但在开发过程中我只是使用这个公共 LDAP 测试服务器

我使用以下类让它工作:

一个简单的 LDAP 配置类。它从我的文件中读取application.properties与 LDAP 相关的属性。

@Configuration
public class LdapConfiguration {

    //Getting values from properties file
    @Value("${ldap.urls}")
    private String ldapUrls;
    @Value("${ldap.base.dn}")
    private String ldapBaseDn;
    @Value("${ldap.username}")
    private String ldapSecurityPrincipal;
    @Value("${ldap.password}")
    private String ldapPrincipalPassword;
    @Value("${ldap.user.dn.pattern}")
    private String ldapUserDnPattern;
    @Value("${ldap.enabled}")
    private String ldapEnabled;

    public LdapConfiguration() {
    }

    ... getters and setters ...

}

还有一个 WebSecurityConfiguration,它实际上从 LdapConfiguration 类中读取以将其用于身份验证:

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private LdapConfiguration ldapConfiguration;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
                .formLogin();
    }

    // Update configure method for the online test server
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .ldapAuthentication()
                .contextSource()
                .url(ldapConfiguration.getLdapUrls() +ldapConfiguration.getLdapBaseDn())
                .managerDn(ldapConfiguration.getLdapSecurityPrincipal())
                .managerPassword(ldapConfiguration.getLdapPrincipalPassword())
                .and()
                .userDnPatterns(ldapConfiguration.getLdapUserDnPattern());
    }  

使用此配置,LDAP 身份验证工作:我得到一个带有登录表单的漂亮 HTML 页面,并使用正确的凭据,我可以使用该网站。登录表单

这是我的问题:在登录阶段之后,如果我运行类似

    UserDetails ud = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    System.out.println(ud);

这就是我会得到的:

LdapUserDetailsImpl@fd8cece1:
    Dn: uid=tesla,dc=example,dc=com; 
    Username: tesla; 
    Password: [PROTECTED]; 
    Enabled: true; 
    AccountNonExpired: true; 
    CredentialsNonExpired: true; 
    AccountNonLocked: true; 
    Granted Authorities: ROLE_SCIENTISTS

我对特斯拉的全名一无所知(在 LDAP 服务器中,作为 field CN)。获得有关经过身份验证的用户的所有数据会很好。

当然,我可以对 LDAP 服务器运行单独的查询,询问有关用户的详细信息 username tesla。但是,这意味着向 LDAP 服务器发出额外的请求,因此这似乎不是一个好的解决方案。

当我执行身份验证时,有没有办法指定我想从 LDAP 服务器获取哪些字段?(在使用 Active Directory 服务器时,它会发生很大变化吗?)

提前致谢。

标签: springspring-bootauthenticationactive-directoryldap

解决方案


推荐阅读