SSM+Apache shiro--ehcache緩存清理

使用ehache進行緩存,能夠再登錄認證成功後緩存認證受權及權限信息,可是用戶退出時,該用戶對應的權限信息不能進行實時更新,因此要求在用戶退出系統時能夠清理其對應的權限信息緩存。apache

在配置ehcache緩存是咱們配置了myshiroCache,並在myrealm中指定了權限緩存的名字,因此在用戶退出時就能夠經過cacheManager及緩存名字獲取該信息,並清理,實現退出系統時清理權限信息。緩存

package com.copsec.railway.im.util;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;public class ShiroAuthorizationHelper {

    private static CacheManager cacheManager;

    private static Logger logger = Logger.getLogger(ShiroAuthorizationHelper.class);

    /**
     * 清除用戶的權限
     * 
     *
     * @param principal 登錄用戶對應的principal對象
     */
    public static void clearAuthorizationInfo(SimplePrincipalCollection principal) {
        logger.info("clear the user: " + principal.toString() + "'s authorizationInfo");
        Cache<Object, Object> cache = cacheManager.getCache("myShiroCache");
        cache.remove(principal);
    }

    /**
     * 清除當前用戶的權限
     */
    public static void clearAuthorizationInfo() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            Subject subject = SecurityUtils.getSubject();
            String username = subject.getPrincipal().toString();
            String realmName = subject.getPrincipals().getRealmNames().iterator().next();
            SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(username, realmName);
            logger.debug("get user principalCollection :"+principalCollection);
            // 調用清理用戶權限
            clearAuthorizationInfo(principalCollection);
        }
    }

    /**
     * 由Spring bean將對象注入
     * @param cacheManager
     */
    public static void setCacheManager(CacheManager cacheManager) {
        
        ShiroAuthorizationHelper.cacheManager = cacheManager;
    }


}

完成後便可在logout controller中調用,進行清理權限信息。spa

相關文章
相關標籤/搜索