Spring BadCredentials事件未触发

时间:2015-05-16 16:47:13

标签: java spring spring-security

如果用户尝试使用错误的凭据进行身份验证,我想记录。因此,我已将此事件侦听器类添加到我的项目中:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationFailureListener
        implements ApplicationListener<AuthenticationFailureBadCredentialsEvent>{

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        System.out.println("test");
        logger.info("test2");
    }
}

问题是根本不起作用。我使用Spring Security默认登录页面。该页面显示&#34;不良凭据&#34;使用错误的凭据时出错,但上面的方法没有被调用。 我有一个非常相似的成功事件监听器代码,它的工作非常好:

@Component
public class AuthenticationSuccessListener implements
        ApplicationListener<InteractiveAuthenticationSuccessEvent> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired private UserService users;

    @Override
    public void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) {
        User user = users.get(event.getAuthentication().getName());
        boolean isAdmin = user.getRole().equals(User.ROLE_ADMIN);
        logger.info((isAdmin ? "Admin" : "User") + " with id " + user.getIdLink()
                + " has successfully logged in!");
    }
}

这是我的Spring Security Java配置:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    private CustomUserDetailsService userDetailsService;

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .formLogin()
                .and()
            .httpBasic();
    }
}

我不知道在这里发生了什么,非常感谢!

春季版:4.0.9
Spring Security版本:3.2.5(也尝试过4.0.1)

编辑:

好的,我为Spring设置了日志级别为DEBUG,但没有。我搜索了&#34; Listener&#34;并且日志指出已创建AuthenticationFailureListener和AuthenticationSuccessListener的实例而没有任何错误。

我甚至将日志放入差异工具(在替换所有时间和检查之后)并与代码版本进行比较,其中FailureListener代码被注释掉,但没有找到任何东西。如果您愿意,可以自己搜索:
https://www.diffchecker.com/cwdn4sp4
在页面底部,您将在左侧找到纯日志文本。

Edit2:部分解决

Serges解决方案有帮助,这是我对onAuthenticationFailure方法的完整实现:​​

@Override
public void onAuthenticationFailure(
        HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {

    if (exception instanceof BadCredentialsException) {
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        Authentication auth =
                new UsernamePasswordAuthenticationToken(name, password);
        eventPublisher.publishEvent(
                new AuthenticationFailureBadCredentialsEvent(auth, exception));
    }
    super.onAuthenticationFailure(request, response, exception);
}

3 个答案:

答案 0 :(得分:10)

我以不同的方式工作。

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    // Inject applicationEventPublisher
    @Inject
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private CustomUserDetailsService userDetailsService;

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

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            // configure a auth event publisher
            .authenticationEventPublisher(new DefaultAuthenticationEventPublisher(applicationEventPublisher))
            .userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .formLogin()
                .and()
            .httpBasic();
    }
}

通过这些更改,我的事件侦听器能够接收身份验证失败事件。 这是spring-security 4.0.2.RELEASE和spring-boot 1.2.5.RELEASE

希望它有所帮助。

答案 1 :(得分:7)

那是按设计

AbstractAuthenticationProcessingFilter的Javadoc很清楚:

活动发布:

如果身份验证成功,将通过应用程序上下文发布InteractiveAuthenticationSuccessEvent。 如果身份验证不成功,则不会发布任何事件,因为这通常会通过特定于AuthenticationManager的应用程序事件进行记录。

(强调我的)

如果要明确发送身份验证失败事件,可以使用自定义AuthenticationFailureHandler扩展SimpleUrlAuthenticationFailureHandler来发送事件并调用基类onAuthenticationFailure方法。

public class EventSendingAuthenticationFailureHandler
        extends SimpleUrlAuthenticationFailureHandler,
        implements ApplicationEventPublisherAware {

    protected ApplicationEventPublisher eventPublisher;

    public void setApplicationEventPublisher(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }

    @Override
    void onAuthenticationFailure(javax.servlet.http.HttpServletRequest request,
                       javax.servlet.http.HttpServletResponse response,
                       AuthenticationException exception)
                         throws IOException,
                                javax.servlet.ServletException {
        // use eventPublisher to publish the event according to exception
        super.onAuthenticationFailure(request, response, exception);
    }
}

你应该可以这样配置:

@Bean
AuthenticationFailureHandler eventAuthenticationFailureHandler() {
    return new EventSendingAuthenticationFailureHandler();
}

@Autowired
AuthenticationFailureHandler eventAuthenticationFailureHandler;

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .formLogin().failureHandler(eventAuthenticationFailureHandler)
            .and()
        .httpBasic();
}

答案 2 :(得分:0)

使用Spring Security 3.2.8,LoggerListener可以正常工作。有关源代码,请参阅Grepcode

您的adpoted代码:

@Named
public class AuthenticationSuccessListener implements ApplicationListener<AbstractAuthenticationEvent> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Inject
    private UserService users;

    @Override
    public void onApplicationEvent(AbstractAuthenticationEvent event) {

        if (event instanceof InteractiveAuthenticationSuccessEvent) {

            User user = users.get(event.getAuthentication().getName());
            boolean isAdmin = user.getRole().equals(User.ROLE_ADMIN);
            logger.info((isAdmin ? "Admin" : "User") + " with id " + user.getIdLink() + " has successfully logged in!");
        }
    }
}