I use spring-boot 2.6.8 with spring security
When user don't enter correct information, i would like to do an operation. So I created this class.
@Component
public class AuthenticationFailureEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent {
private LoginAttemptService loginAttemptService;
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
loginAttemptService.loginFailed(e.getAuthentication().getName(), auth.getRemoteAddress());
}
}
If a user enter a bad password, this event is never called
Edit
For the security, I have this
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AuthenticationEventPublisher authenticationEventPublisher;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher).userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
...
}
CodePudding user response:
The events are not published out of the box. You need to also declare an AuthenticationEventPublisher
with code like this:
@Bean
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher applicationEventPublisher
) {
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
}
Please also have a look at this part of the reference documentation: https://docs.spring.io/spring-security/reference/servlet/authentication/events.html