多個realm時,拋出自定義的異常

1.繼承一個ModularRealmAuthenticator類

建立一個類,繼承ModularRealmAuthenticator ,而後重寫 doMultiRealmAuthentication方法java

/**
  * ,拋出realm中第一個遇到的異常
  * @param realms 領域認證器
  * @param token 認證憑證
  * @return aggregate
  */
@Override
protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
    AuthenticationStrategy strategy = getAuthenticationStrategy();
    AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
    if (log.isTraceEnabled()) {
        log.trace("Iterating through {} realms for PAM authentication", realms.size());
    }
    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;
            //有異常今後處拋出
            info = realm.getAuthenticationInfo(token);
            aggregate = strategy.afterAttempt(realm, token, info, aggregate, null);
        } else {
            log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
        }
    }
    aggregate = strategy.afterAllAttempts(token, aggregate);
    return aggregate;
}

2.在shiroConfig中把自定義的 ModularRealmAuthenticator 加入到shiro中

/**
     * shiro 安全管理器設置
     * @return SecurityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager());
        //自定義的模塊化領域認證(ModularRealmAuthenticator)
        ModularRealmAuthenticator authenticator = new WxModularRealmAuthenticator();
        securityManager.setAuthenticator( authenticator );
        return securityManager;
    }
相關文章
相關標籤/搜索