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("出现了这个异常。。。但是不管他,因为我也不知道怎么处理");
}


瞎搞一通,总之解决了问题,但是个人觉得有点不理想,算了,希望可以找到更好的解决方法。

 

  

点赞