How can I limit login attempts in Spring Security?

后端 未结 7 1458
清酒与你
清酒与你 2020-12-08 08:11

Is there some configuration or available module in Spring Security to limit login attempts (ideally, I\'d like to have an increasing wait time between subsequent failed atte

7条回答
  •  长情又很酷
    2020-12-08 08:22

    As suggested by Rob Winch in http://forum.springsource.org/showthread.php?108640-Login-attempts-Spring-security, I just subclassed DaoAuthenticationProvider (which could also have been done using an aspect as Ritesh suggests) to limit the number of failed logins, but you could also assert pre-conditions as well:

    public class LimitingDaoAuthenticationProvider extends DaoAuthenticationProvider {
      @Autowired
      private UserService userService;
        @Override
        public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
          // Could assert pre-conditions here, e.g. rate-limiting
          // and throw a custom AuthenticationException if necessary
    
          try {
            return super.authenticate(authentication);
          } catch (BadCredentialsException e) {
            // Will throw a custom exception if too many failed logins have occurred
            userService.recordLoginFailure(authentication);
            throw e;
          }
       }
    }
    

    In Spring config XML, simply reference this bean:

    
    
    
        
    
    

    Note that I think that solutions which rely on accessing an AuthenticationException's authentication or extraInformation properties (such as implementing an AuthenticationFailureHandler) should probably not be used because those properties are now deprecated (in Spring Security 3.1 at least).

提交回复
热议问题