How can I limit login attempts in Spring Security?

后端 未结 7 1456
清酒与你
清酒与你 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:47

    Here is my implementation, hope help.

    1. Create a table to store any invalid login attempts.
    2. If invalid attempts > max allowed, set UserDetail.accountNonLocked to false
    3. Spring Security will handle the "lock process" for you. (refer to AbstractUserDetailsAuthenticationProvider)

    Last, extends DaoAuthenticationProvider, and integrate the logic inside.

    @Component("authenticationProvider")
    public class YourAuthenticationProvider extends DaoAuthenticationProvider {
    
    @Autowired
    UserAttemptsDao userAttemptsDao;
    
    @Override
    public Authentication authenticate(Authentication authentication) 
          throws AuthenticationException {
    
      try {
    
        Authentication auth = super.authenticate(authentication);
    
        //if corrent password, reset the user_attempts
        userAttemptsDao.resetFailAttempts(authentication.getName());
    
        return auth;
    
      } catch (BadCredentialsException e) { 
    
        //invalid login, update user_attempts, set attempts+1 
        userAttemptsDao.updateFailAttempts(authentication.getName());
    
        throw e;
    
      } 
    
    }
    
    
    }
    

    For full source code and implementation, please refer to this - Spring Security limit login attempts example,

    0 讨论(0)
提交回复
热议问题