1、添加ModularRealmAuthenticator的继承类:
package cn.cfae.bcbbs.common.security.realms;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
/**
* @description: shiro在多realm的情况下,会出现异常只返回AuthenticationException的情况,此方法作用为阻止这种情况。
* @author: ljy
* @date: 2021/1/15
* @version: 1.0
*/
public class MultiRealmAuthenticator 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;
}
}
2、配置xml文件中 身份认证器
<!-- 身份认证器 -->
<bean id="authenticator" class="cn.xxx.common.security.realms.MultiRealmAuthenticator">
<!-- 验证规则:通过 AuthenticationStrategy 接口指定,提供以下三个实现,默认为AtLeastOneSuccessfulStrategy -->
<property name="authenticationStrategy">
<!-- 只要有一个 Realm 验证成功即可,只返回第一个 Realm 身份验证成功的认证信息,其他的忽略; -->
<!-- <bean class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"/> -->
<!-- 默认:只要有一个 Realm 验证成功即可, 和 FirstSuccessfulStrategy不同,返回所有 Realm 身份验证成功的认证信息; -->
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>
<!-- 所有 Realm 验证成功才算成功,且返回所有 Realm 身份验证成功的认证信息,如果有一个失败就失败了 -->
<!-- <bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/> -->
</property>
</bean>
3、登录接口如下拦截: