1. 程式人生 > >Shiro密碼重試次數限制

Shiro密碼重試次數限制

如在 1 個小時內密碼最多重試 5 次,如果嘗試次數超過 5 次就鎖定 1 小時,1 小時後可再次重試,如果還是重試失敗,可以鎖定如 1 天,以此類推,防止密碼被暴力破解。我們通過繼承 HashedCredentialsMatcher,且使用 Ehcache 記錄重試次數和超時時間。

public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
       String username = (String)token.getPrincipal();
        //retry count + 1
        Element element = passwordRetryCache.get(username);
        if(element == null) {
            element = new Element(username , new AtomicInteger(0));
            passwordRetryCache.put(element);
        }
        AtomicInteger retryCount = (AtomicInteger)element.getObjectValue();
        if(retryCount.incrementAndGet() > 5) {
            //if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if(matches) {
            //clear retry count
            passwordRetryCache.remove(username);
        }
        return matches;
}

如上程式碼邏輯比較簡單,即如果密碼輸入正確清除 cache 中的記錄;否則 cache 中的重試次數 +1,如果超出 5 次那麼丟擲異常表示超出重試次數了。


QQ群:785071190
檢視原文:http://www.coder306.cn/?p=209