Проверка подлинности LDAP Spring - неверные учетные данные - PullRequest
0 голосов
/ 14 ноября 2018

Я пытаюсь реализовать аутентификацию LDAP и создать JWT весной. Я получаю ошибку Bad credentials и не могу понять, что мне не хватает в реализации, пожалуйста, дайте мне некоторую информацию, если можете. Я включил весеннюю отладку безопасности, но ничего не пришло оттуда, чтобы понять основную причину.

Вот контроллер

Path("/test")
public class AuthenticationController {

    private static final Logger logger = LogManager.getLogger(AuthenticationController.class);

    private AuthenticationManager authenticationManager;
    private JwtProvider jwtProvider;

    @Autowired
    public AuthenticationController(AuthenticationManager authenticationManager, JwtProvider jwtProvider){

        this.authenticationManager = authenticationManager;
        this.jwtProvider = jwtProvider;
    }

    @Path("/login")
    @POST
    @Produces(MediaType.APPLICATION_JSON_VALUE)
    @Consumes(MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> Authorization(@Valid LoginRequest loginRequest){

        if(loginRequest.getUsername().isEmpty() || loginRequest.getPassword().isEmpty()){
            throw new com.ing.istore.exceptions.CustomHttpError("Invalid Credentials Entered",HttpStatus.UNAUTHORIZED);
        }

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),loginRequest.getPassword()));


        String jwt = jwtProvider.generateJwtToken(authentication);

        return ResponseEntity.ok(new JwtResponse(jwt));

}
    }

Класс провайдера Jwt

@Component
public class JwtProvider {

    private static final Logger logger = LogManager.getLogger(JwtProvider.class);

    private AuthConfiguration authConfiguration;

    @Autowired
    public JwtProvider(AuthConfiguration authConfiguration){
        this.authConfiguration = authConfiguration;
    }

    public String generateJwtToken(Authentication authentication) {

        LdapUserDetailsImpl userPrincipal = (LdapUserDetailsImpl) authentication.getPrincipal();

        Instant time = Instant.now();
        Date d = Date.from(time.plus(15, ChronoUnit.MINUTES));
        return Jwts.builder()
                .setSubject((userPrincipal.getUsername()))
                .setIssuedAt(new Date())
                .setExpiration(d)
                .signWith(SignatureAlgorithm.HS512, authConfiguration.getSecretKey())
                .compact();
    }

    public boolean validateJwtToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(authConfiguration.getSecretKey()).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException e) {
            logger.error("Invalid JWT signature -> Message: {} ", e);
        } catch (MalformedJwtException e) {
            logger.error("Invalid JWT token -> Message: {}", e);
        } catch (ExpiredJwtException e) {
            logger.error("Expired JWT token -> Message: {}", e);
        } catch (UnsupportedJwtException e) {
            logger.error("Unsupported JWT token -> Message: {}", e);
        } catch (IllegalArgumentException e) {
            logger.error("JWT claims string is empty -> Message: {}", e);
        }

        return false;
    }

    public String getUserNameFromJwtToken(String token) {
        return Jwts.parser()
                .setSigningKey(authConfiguration.getSecretKey())
                .parseClaimsJws(token)
                .getBody().getSubject();
    }
}

И конфигурация WebSecurity для Spring также ниже

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(
        securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Bean(BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .ldapAuthentication()
                .userDnPatterns("uid={0},ou=people")
                .groupSearchBase("ou=groups")
                .contextSource(contextSource()).passwordCompare();

                }


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

        http
                .csrf()
                .disable()
                .cors()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(unauthorizedHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/test/login/").permitAll()
                .anyRequest().authenticated();
    }

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
    public DefaultSpringSecurityContextSource contextSource() {
        return  new DefaultSpringSecurityContextSource(
                Collections.singletonList("ldaps://xxx.xxx.xxx:636/"),"ou=people,o=COMPANY");
    }

    }

Поэтому, когда я пытаюсь запустить URL для входа в систему, я получаю сообщение об ошибке

[https-jsse-nio-8086] DEBUG o.s.s.a.ProviderManager - Authentication attempt using org.springframework.security.ldap.authentication.LdapAuthenticationProvider 
[https-jsse-nio-8086] DEBUG o.s.s.l.a.LdapAuthenticationProvider - Processing authentication request for user: xxxxx 
[https-jsse-nio-8086] DEBUG o.s.l.c.s.AbstractContextSource - Got Ldap context on server 'ldaps://xxx.xxx.xxx:636/ou=people,o=COMPANY' 
[https-jsse-nio-8086] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener' 
[https-jsse-nio-8086] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Authentication exception occurred; redirecting to authentication entry point 
org.springframework.security.authentication.BadCredentialsException: Bad credentials
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...