Jhipster Ldap集成错误凭证错误

问题描述

我正在尝试将Jhipster与forumsys online Ldap server 集成。但是我总是会收到 Bad Credentials 错误消息。我通过spring-boot ldap sample

获得成功

我已经跟踪了这个issue,但是它已关闭

我该如何解决这个问题? 感谢您的回复

SecurityConfiguration.java

no-answer

CustomAuthenticationManager.java:

package com.test.portal.config;

import com.test.portal.security.*;
import com.test.portal.security.jwt.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.filter.CorsFilter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final TokenProvider tokenProvider;

    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;

    public SecurityConfiguration(TokenProvider tokenProvider,CorsFilter corsFilter,SecurityProblemSupport problemSupport) {
        this.tokenProvider = tokenProvider;
        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

      
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  
        auth.ldapAuthentication().userSearchFilter("(cn={0})")
    
     
      .contextSource(getContextSource());
    }
  
    @Bean
    public LdapContextSource getContextSource () {
        LdapContextSource contextSource= new LdapContextSource();
        contextSource.setUrl("ldap://ldap.forumsys.com:389");
        contextSource.setBase("ou=mathematicians,dc=example,dc=com");
        contextSource.setUserDn("cn=read-only-admin,dc=com");
        contextSource.setPassword("password"); 
        contextSource.afterPropertiesSet();
        return contextSource;
    }
  
  
  
 

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .disable()
            .addFilterBefore(corsFilter,UsernamePasswordAuthenticationFilter.class)
            .exceptionHandling()
                .authenticationEntryPoint(problemSupport)
                .accessDeniedHandler(problemSupport)
        .and()
            .headers()
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
        .and()
            .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
        .and()
            .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
        .and()
            .frameOptions()
            .deny()
        .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
            .authorizeRequests()
            .antMatchers("/api/authenticate").permitAll()
            .antMatchers("/api/register").permitAll()
            .antMatchers("/api/activate").permitAll()
            .antMatchers("/api/account/reset-password/init").permitAll()
            .antMatchers("/api/account/reset-password/finish").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll() 
        .and()
            .httpBasic()
        .and()
            .apply(securityConfigurerAdapter());
        // @formatter:on
    }

    private JWTConfigurer securityConfigurerAdapter() {
        return new JWTConfigurer(tokenProvider);
    }
}

错误消息:

package com.test.portal.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;

import com.test.portal.domain.Authority;
import com.test.portal.domain.User;
import com.test.portal.repository.UserRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationManager implements AuthenticationManager {

    LdapAuthenticationProvider provider = null;

    private static final Logger log = LoggerFactory.getLogger(CustomAuthenticationManager.class);

    private final UserRepository userRepository;

    @Autowired
    private final LdapContextSource ldapContextSource;

    public CustomAuthenticationManager(UserRepository userRepository,LdapContextSource ldapContextSource) {
        this.userRepository = userRepository;
        this.ldapContextSource = ldapContextSource;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        log.debug("AUTHENTICATION Login " + authentication.getName());
        log.debug("AUTHENTICATION Password " + authentication.getCredentials().toString());

        log.debug("AUTHENTICATION ldapContextSource > " + ldapContextSource);
        BindAuthenticator bindAuth = new BindAuthenticator(ldapContextSource);
        log.debug("AUTHENTICATION bindAuth> " + bindAuth);
        FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch("","(uid={0})",ldapContextSource);
        log.debug("AUTHENTICATION userSearchk> " + userSearch);
        try {
            bindAuth.setUserSearch(userSearch);
            log.debug("AUTHENTICATION bindAuth.setUserSearch> " + bindAuth);
            bindAuth.afterPropertiesSet();
            log.debug("AUTHENTICATION bindAuth.afterPropertiesSet> " + bindAuth);
        } catch (Exception ex) {
            log.debug("AUTHENTICATION EXCEPTION>" + ex);
           // java.util.logging.Logger.getLogger(CustomAuthenticationManager.class.getName()).log(Level.SEVERE,null,ex);
        } 
        provider = new LdapAuthenticationProvider(bindAuth);
        log.debug("AUTHENTICATION provider>" + provider);
        provider.setUserDetailsContextMapper(new UserDetailsContextMapper() {
            @Override
            public UserDetails mapUserFromContext(DirContextOperations ctx,String username,Collection<? extends GrantedAuthority> clctn) {
                
                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                        "ROLE_ADMIN");
                grantedAuthorities.add(grantedAuthority);
                  return new org.springframework.security.core.userdetails.User(
                    username,"1",grantedAuthorities);    
            }

            @Override
            public void mapUserToContext(UserDetails ud,DirContextAdapter dca) {

            }
        });
 
        return provider.authenticate(authentication);
    }

    
} 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)