我通过激发 Baeldung 的“使用 Spring Security 防止暴力验证尝试”页面为我的登录服务实现了一种暴力防止机制,如下所示:
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
private final UserService userService;
private final LoginAttemptService loginAttemptService;
public UserTokenDTO login(final LoginRequest request) {
if(!user.isValid) {
throw new InvalidCredentialsException();
}
// code omitted for brevity
}
}
当用户未经验证时,LoginService
抛出InvalidCredentialsException()
然后我试图在AuthenticationFailureListener
课堂上捕获此异常:
@Component
public class AuthenticationFailureListener implements
ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
@Autowired
private HttpServletRequest request;
@Autowired
private LoginAttemptService loginAttemptService;
@Override
public void onApplicationEvent(final AuthenticationFailureBadCredentialsEvent e) {
final String xfHeader = request.getHeader("X-Forwarded-For");
if (xfHeader == null) {
loginAttemptService.loginFailed(request.getRemoteAddr());
} else {
loginAttemptService.loginFailed(xfHeader.split(",")[0]);
}
}
}
当出现错误时,loginAttemptService.loginFailed()
将调用方法。但是,我无法在我的onApplicationEvent()
. 我曾尝试使用不同的事件类型,但对于某些事件,例如ApplicationEvent
它在每个事件上触发,我应该仅在用户未通过身份验证时触发它InvalidCredentialsException
。
进行搜索后,我发现我需要进行配置,以便 Spring Security 在失败或成功时捕获这些事件。但是定义不清楚,我想也许我可以通过在我的AuthenticationFailureListener
班级中使用正确的事件类型来捕捉事件。我也有一个事件处理程序类,但我不确定它是否有帮助。
更新:这是我的SecurityConfig
. 我仍然不能开火AuthenticationFailureBadCredentialsEvent
,也不能得到任何例外onApplicationEvent
。
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
AuthenticationFailureHandler eventAuthenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
private final AuthenticationFailureHandler eventAuthenticationFailureHandler;
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin().failureHandler(eventAuthenticationFailureHandler)
.and()
.httpBasic();
}
}
正如下面链接的帖子中所写
如果身份验证成功,InteractiveAuthenticationSuccessEvent 将通过应用程序上下文发布。如果身份验证不成功,则不会发布任何事件,因为这通常会通过特定于 AuthenticationManager 的应用程序事件进行记录。
检查此讨论可能有助于找到适合您需求的解决方案Spring BadCredentials 事件未触发
如果您发现这有帮助并解决了您的问题,请不要忘记将此作为正确答案(并且不要忘记为另一篇文章中的那个人点赞,他应得的)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句