使用ehache进行缓存,可以再登陆认证成功后缓存认证授权及权限信息,但是用户退出时,该用户对应的权限信息不能进行实时更新,所以要求在用户退出系统时可以清理其对应的权限信息缓存。
在配置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中调用,进行清理权限信息。