我使用 spring-boot 2.6.8 和 spring security
當用戶沒有輸入正確的資訊時,我想做一個操作。所以我創建了這個類。
@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());
}
}
如果用戶輸入了錯誤的密碼,則永遠不會呼叫此事件
編輯
為了安全,我有這個
@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);
}
...
}
uj5u.com熱心網友回復:
這些事件不是開箱即用的。您還需要宣告一個AuthenticationEventPublisherwith 代碼,如下所示:
@Bean
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher applicationEventPublisher
) {
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
}
另請查看參考檔案的這一部分:https ://docs.spring.io/spring-security/reference/servlet/authentication/events.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486394.html
