customAuthenticationProvider两次调用身份验证

时间:2018-04-20 03:11:53

标签: java authentication spring-boot custom-authentication

我已经研究了这个,我认为评论(实际上在这个帖子中的答案:ProviderManager.authenticate called twice for BadCredentialsException)将是我的解决方案......但我仍然得到双重提交/要求进行身份验证。第二个每次都有一个空密码。第一个电话有证书。

下面是Java Config类和CustomAuthProvider类..

@Configuration
@EnableWebSecurity
public class UserWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 
@Override
protected void configure(HttpSecurity http) throws Exception {
    //@formatter:off
    http.antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/", "/home**", "/login**","/create_user")
            .permitAll().anyRequest().authenticated()
        .and()
            .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/login")
            .failureUrl("/login?error")
        .and()
            .logout()
            .logoutSuccessUrl("/login?logout")
            .permitAll()
        .and()
            .exceptionHandling().accessDeniedPage("/login?denied") //in this simple case usually due to a InvalidCsrfTokenException after session timeout
        .and()
            .csrf()
                .ignoringAntMatchers("/rest/**")
        .and()
            .sessionManagement().enableSessionUrlRewriting(false)
        .and()
            .headers().frameOptions().deny();
}

...然后是customAuthProvider ......

@Component
public class CustomAuthProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication.getName() == null) {
        logger.warn("empty userName");
        return null;
    }

    if (authentication.getCredentials() == null) {
        logger.warn("empty password");
        return null;
    }

// code to check credentials etc ...

 if (!(user != null && userHash.equals(storedHash))) {
        System.out.println("fail");
        return  null;
    }

    return new UsernamePasswordAuthenticationToken(user,password);

}

1 个答案:

答案 0 :(得分:0)

将auth提供程序代码修改为以空的授权列表结束并返回authenticationToken ...现在它可以正常工作。

// ...        
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,password, new ArrayList<>());
return authenticationToken;