LDAP身份验证春季-错误凭证

时间:2018-11-13 23:00:08

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

我正在尝试实现LDAP身份验证并在Spring中创建JWT。我收到了错误的凭证错误,并且我无法弄清实施中缺少的内容,如果可以的话,请给我一些信息。我已经启用了Spring Security调试功能,但是为了理解根本原因,什么也没做。

这是控制者

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();
    }
}

Spring的WebSecurity配置也在下面

@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");
    }

    }

因此,当我尝试运行登录网址时,出现错误

[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

0 个答案:

没有答案