ProviderManager.authenticate为BadCredentialsException调用了两次

时间:2015-11-18 18:56:15

标签: spring spring-security

Spring 4.1和Spring Security 3.2: 我们实现了自定义身份验证提供程序,如果用户输入的密码不正确,则会引发BadCredentialsException。 抛出BadCredentialsException时,将调用ProviderManager.authenticate方法,该方法再次调用自定义身份验证中的authenticate方法。抛出LockedException时,不会再次调用自定义身份验证提供程序中的authenicate方法。我们计划保留登录尝试次数,因此我们不希望两次调用authenticate方法。有谁知道为什么自定义身份验证类中的authenticate方法会被调用两次?

WebConfig:


  @Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    private AMCiUserDetailsService userDetailsService;

    @Autowired
    private CustomImpersonateFailureHandler impersonateFailureHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/jsp/*.css","/jsp/*.js","/images/**").permitAll()  
                .antMatchers("/login/impersonate*").access("hasRole('ADMIN') or hasRole('ROLE_PREVIOUS_ADMINISTRATOR')") 
                .anyRequest().authenticated()                                    
                .and()
            .formLogin()
                .loginPage("/login.jsp")
                .defaultSuccessUrl("/jsp/Home.jsp",true)                
                .loginProcessingUrl("/login.jsp")                                 
                .failureHandler(loginFailureHandler)
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login.jsp?msg=1")
                .permitAll()
                .and()
            .addFilter(switchUserFilter())
            .authenticationProvider(customAuthenticationProvider);

            http.exceptionHandling().accessDeniedPage("/jsp/SecurityViolation.jsp");  //if user not authorized to a page, automatically forward them to this page.
            http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN)); 
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }

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

    //Used for the impersonate functionality
    @Bean CustomSwitchUserFilter switchUserFilter() {
        CustomSwitchUserFilter filter = new CustomSwitchUserFilter();
        filter.setUserDetailsService(userDetailsService);
        filter.setTargetUrl("/jsp/Impersonate.jsp?msg=0");
        filter.setSwitchUserUrl("/login/impersonate");
        filter.setExitUserUrl("/logout/impersonate");
        filter.setFailureHandler(impersonateFailureHandler);
        return filter;
    }
}

自定义身份验证提供程序:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired(required = true)
    private HttpServletRequest request;

    @Autowired
    private AMCiUserDetailsService userService;

    @Autowired
    private PasswordEncoder encoder;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = authentication.getName().trim();
        String password = ((String) authentication.getCredentials()).trim();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BadCredentialsException("Login failed! Please try again.");
        }


        UserDetails user;
        try {
            user = userService.loadUserByUsername(username);
            //log successful attempt
            auditLoginBean.setComment("Login Successful");
            auditLoginBean.insert(); 
        } catch (Exception e) {
             try {
                //log unsuccessful attempt
                auditLoginBean.setComment("Login Unsuccessful");
                auditLoginBean.insert();
             } catch (Exception e1) {
                // TODO Auto-generated catch block
             }
            throw new BadCredentialsException("Please enter a valid username and password.");
        }

        if (!encoder.matches(password, user.getPassword().trim())) {
            throw new BadCredentialsException("Please enter a valid username and password.");
        }

        if (!user.isEnabled()) {
            throw new DisabledException("Please enter a valid username and password.");
        }

        if (!user.isAccountNonLocked()) {
            throw new LockedException("Account locked. ");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        List<GrantedAuthority> permlist = new ArrayList<GrantedAuthority>(authorities);

        return new UsernamePasswordAuthenticationToken(user, password, permlist);
    }


    public boolean supports(Class<? extends Object> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

2 个答案:

答案 0 :(得分:6)

原因是您添加了两次身份验证提供程序,一次configure(HttpSecurity),一次configure(AuthenticationManagerBuilder)。这将创建一个ProviderManager,其中包含两个项目,两者都是您的提供者。

处理身份验证时,将按顺序询问提供程序,直到成功,除非抛出LockedException或类似的状态异常,否则循环将中断。

答案 1 :(得分:1)

可能存在一个你不会覆盖configure(AuthenticationManagerBuilder)的情况,并且仍然会像Phil在他的评论中提到的那样AuthenticationProver authenticate方法被调用两次接受的答案。

为什么?

原因是,当您不覆盖configure(AuthenticationManagerBuilder)并拥有AuthenticationProvider bean时,它将由Spring Security注册,您不必做任何其他事情。

但是,当configure(AuthenticationManagerBuilder)被覆盖时,Spring Security将调用它并且不会尝试单独注册任何提供程序。 如果您有好奇心,可以查看related method。如果您覆盖disableLocalConfigureAuthenticationBldr,则configure(AuthenticationManagerBuilder)为真。

因此,简而言之,如果您只想注册一个自定义AuthenticationProvider,请不要覆盖configure(AuthenticationManagerBuilder),请不要在authenticationProvider(AuthenticationProvider)中致电configure(HttpSecurity),只需制作您的AuthenticationProviver 1}}通过注释@Component实现bean,你很高兴。