如何在Spring Boot中获取LDAP用户名

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Spring Boot中获取LDAP用户名相关的知识,希望对你有一定的参考价值。

当用户尝试在Springboot中使用Active Directory进行身份验证时,如何获取用户名。

正如我尝试使用下面的代码但得到错误,如下所示:

LDAP Config:

#ldap.url=ldap://localhost:389

#ldap.base.dn=dc=springframework,dc=org
#ldap.user.dn.pattern=(&(objectClass=user)(userPrincipalName={0})(memberof=CN=GroupACCESS,OU=people, DC=springframework,DC=org))

WebSecurityConfig.java

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        private final static Logger log = LogManager.getLogger(WebSecurityConfig.class);

        @Value("${ldap.urls}")
        private String ldapUrl;

        @Value("${ldap.base.dn}")
        private String ldapDomain;

        @Value("${ldap.user.dn.pattern}")
        private String ldapUserDnPattern;


        @Override
        protected void configure(HttpSecurity http) throws Exception {

          http.addFilterBefore(
                  new CustomFilter(), UsernamePasswordAuthenticationFilter.class);

            http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider(
                    this.ldapDomain, this.ldapUrl);

            adProvider.setConvertSubErrorCodesToExceptions(true);
            adProvider.setUseAuthenticationRequestCredentials(true);


            // Checks with the Distinguished Name pattern provided
            if (this.ldapUserDnPattern != null && this.ldapUserDnPattern.trim().length() > 0) {

                adProvider.setSearchFilter(this.ldapUserDnPattern);

                Authentication auth1 = SecurityContextHolder.getContext().getAuthentication();
                String userName = auth1.getName();
                String password = (String)auth1.getCredentials();

                log.info("userName:"+userName);
            }


            auth.authenticationProvider(adProvider);

        }
    }

请查找错误日志,如下所示:

 [ERROR] 2018-08-23 15:13:53.376 [restartedMain] SpringApplication - Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE]

任何人都可以请看看这个并帮助我。

答案

将以下过滤器添加到WebSecurityConfigurerAdapter以从请求中读取用户名参数:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().addFilterBefore(new Filter() {

            public void init(FilterConfig filterConfig) throws ServletException {

            }

            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                if (request.getParameter("username")!=null) System.out.println(request.getParameter("username"));
                chain.doFilter(request, response);
            }

            public void destroy() {

            }
        }, UsernamePasswordAuthenticationFilter.class);
    }

以上是关于如何在Spring Boot中获取LDAP用户名的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义凭据传递给 Spring Boot ldap

Spring Security - 在Spring Boot中针对LDAP使用Active Directory对用户进行身份验证

如何在 Spring Boot 中简化 LDAP 身份验证以减少数据加载过程时间?

spring boot ldap 组和受限端点

在 Spring Security(spring-boot 项目)中使用 ldap 凭据进行 Http 基本身份验证以保护休息服务调用

如何为 LDAP 和 JDBC 配置 Spring?