shiro自定義異常無法被捕獲總是拋出AuthenticationException解決方案


  這個問題我也是出的莫名其妙,剛開始好好的,然后配置多realm之后出的。

  現在直入主題

  在繼承了 org.apache.shiro.authc.pam.ModularRealmAuthenticator的類中重寫doMultiRealmAuthentication方法

  以下是重寫的代碼,判斷是否存在異常。如果存在異常,則拋出。

public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

private static final Logger log = LoggerFactory.getLogger(ModularRealmAuthenticator.class);

@Override
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) throws AuthenticationException {
AuthenticationStrategy strategy = getAuthenticationStrategy();

AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

if (log.isTraceEnabled()) {
log.trace("Iterating through {} realms for PAM authentication", realms.size());
}
AuthenticationException authenticationException = null;
for (Realm realm : realms) {

aggregate = strategy.beforeAttempt(realm, token, aggregate);

if (realm.supports(token)) {

log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);

AuthenticationInfo info = null;
try {
info = realm.getAuthenticationInfo(token);
} catch (AuthenticationException e) {
authenticationException = e;
if (log.isDebugEnabled()) {
String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
log.debug(msg, e);
}
}

aggregate = strategy.afterAttempt(realm, token, info, aggregate, authenticationException);

} else {
log.debug("Realm [{}] does not support token {}. Skipping realm.", realm, token);
}
}
if(authenticationException != null){
throw authenticationException;
}
aggregate = strategy.afterAllAttempts(token, aggregate);

return aggregate;
}
}

 

  關鍵點在於

    if(authenticationException != null){
            throw authenticationException;
        }
 
有可能出現的問題。。。
可能會出現第二個realm會出現第一個realm的拋出的異常。樓主直接在subject.login(token);try處理了。。
如果想在第二個realm里throw new ,別拋出RuntimeException這個就行。。。
try {
    subject.login(token);
}catch (LoginPhoneException e){
    Map map = new HashMap();
    map.put("code", CodeAndMsgEnum.INFO.getCode());
    return map;
}catch (RuntimeException e){
    System.out.println("出現了這個異常。。。但是不管他,因為我也不知道怎么處理");
}


瞎搞一通,總之解決了問題,但是個人覺得有點不理想,算了,希望可以找到更好的解決方法。

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM