I have a simple spring boot application ,that used spring security with jwt filter
All work fine , but when I try to catch authentication success and failed events in my listeners ,
it's not work the authentication events never fired I'm not able to find what's wrong
This's my security class config :
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
new AntPathRequestMatcher("/public/**"),
new AntPathRequestMatcher("/h2-console/**"),
new AntPathRequestMatcher("/v3/api-docs/**"),
new AntPathRequestMatcher("/swagger-ui/**"),
new AntPathRequestMatcher("/swagger-ui.html")
);
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
TokenAuthenticationProvider provider;
SecurityConfig(final TokenAuthenticationProvider provider) {
super();
this.provider = requireNonNull(provider);
}
/* @Override
protected void configure(final AuthenticationManagerBuilder auth) {
auth.authenticationProvider(provider);
}*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher());
}
@Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.and()
.authenticationProvider(provider)
.addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
.authorizeRequests()
.requestMatchers(PROTECTED_URLS)
.authenticated()
.and()
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.logout().disable();
// h2 console config
http.headers().frameOptions().sameOrigin();
}
@Bean
TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
final TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(successHandler());
return filter;
}
@Bean
public DefaultAuthenticationEventPublisher authenticationEventPublisher() {
return new DefaultAuthenticationEventPublisher();
}
@Bean
SimpleUrlAuthenticationSuccessHandler successHandler() {
final SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
successHandler.setRedirectStrategy(new NoRedirectStrategy());
return successHandler;
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* Disable Spring boot automatic filter registration.
*/
@Bean
FilterRegistrationBean disableAutoRegistration(final TokenAuthenticationFilter filter) {
final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
@Bean
AuthenticationEntryPoint forbiddenEntryPoint() {
return new HttpStatusEntryPoint(FORBIDDEN);
}
My TokenAuthenticationFilter is an implementation of the interface : AbstractAuthenticationProcessingFilter
And this my listeners :
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthenticationFailureListener {
private final LoginFailureRepository loginFailureRepository ;
private final UserRepository userRepository;
@EventListener
public void listen(AuthenticationFailureBadCredentialsEvent event){
log.info("Login Failed");
LoginFailure.LoginFailureBuilder builder = LoginFailure.builder();
if(event.getSource() instanceof UsernamePasswordAuthenticationToken){
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) event.getSource();
if(token.getPrincipal() instanceof String){
String userName =(String) token.getPrincipal();
builder.userName(userName);
log.info("Attempted username : {}",userName);
userRepository.findByUsername(userName).ifPresent(builder::user);
}
if(token.getPrincipal() instanceof WebAuthenticationDetails){
WebAuthenticationDetails details =(WebAuthenticationDetails) token.getDetails();
builder.sourceIp(details.getRemoteAddress());
log.info("User remote address : {}",details.getRemoteAddress());
}
}
LoginFailure loginFailure = loginFailureRepository.save(builder.build());
log.info("saving login failure : {}",loginFailure);
}
}
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthenticationSuccessListener {
private final LoginSuccessRepository loginSuccessRepository ;
@EventListener
public void listen(AuthenticationSuccessEvent event){
log.info("--------------- USER LOGGED WITH SUCCESS ----------------------");
LoginSuccess.LoginSuccessBuilder builder = LoginSuccess.builder();
if(event.getSource() instanceof UsernamePasswordAuthenticationToken){
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) event.getSource();
if(token.getPrincipal() instanceof User){
User user =(User) token.getPrincipal();
builder.user(user);
log.info("User name login in : {}",user.getUsername());
}
if(token.getPrincipal() instanceof WebAuthenticationDetails){
WebAuthenticationDetails details =(WebAuthenticationDetails) token.getDetails();
builder.sourceIp(details.getRemoteAddress());
log.info("User remote address : {}",details.getRemoteAddress());
}
}
LoginSuccess loginSuccess = loginSuccessRepository.save(builder.build());
log.info("saving login success : {}",loginSuccess);
}
}
And this's my start logs :
SecurityAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.security.authentication.DefaultAuthenticationEventPublisher' (OnClassCondition)
2021-01-09 21:42:28.413 DEBUG 49828 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'authenticationFailureListener'
2021-01-09 21:42:28.422 DEBUG 49828 --- [ restartedMain] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'authenticationSuccessListener'
question from:
https://stackoverflow.com/questions/65647492/defaultauthenticationeventpublisher-not-fire-event-to-my-eventlistener 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…