Spring Security authenification failure event
For security reasons you need limit failure login attempts in your application, simply you can do it using counter, that updates a count in the DB. Next I will show how to handle this event in Spring Security
1) First aproach is to use AuthentificationFailureHandler:
public class AuthentificationListener implements AuthenticationFailureHandler{
class:
@Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException ae)
throws IOException, ServletException {
UsernamePasswordAuthenticationToken user =(UsernamePasswordAuthenticationToken)ae.getAuthentication();
// user contains required data
response.sendRedirect("login?error=true");
}
spring-confix.xml, need to specify authentication-failure-handler-ref bean:
<security:http auto-config="false" use-expressions="true" access-denied-page="/denied">
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<security:form-login login-page="/login" authentication-failure-handler-ref="myAuthErrorHandler" default-target-url="/test/success"/>
<security:logout invalidate-session="true" logout-success-url="/login" logout-url="/logout" />
</security:http>
2) Other aproach, is much more simple, you need to listen AuthenticationFailure Event:
@Component
public class UserAuthenticationErrorHandler implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {
@Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
Object userName = event.getAuthentication().getPrincipal();
Object credentials = event.getAuthentication().getCredentials();
System.out.println("Failed login using USERNAME " + userName);
System.out.println("Failed login using PASSWORD " + credentials);
}
}
Sursa
2012-07-12 21:26:00