SpringShiro每次请求的权限校验,都会调用一次doGetAuthorizationInfo的问题
Posted 逐知逐行
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringShiro每次请求的权限校验,都会调用一次doGetAuthorizationInfo的问题相关的知识,希望对你有一定的参考价值。
公司项目里用到SpringShiro权限校验,采用Redis做为SecurityManager的缓存管理。在doGetAuthorizationInfo方法打了断点,发现每次的请求,都会调用一次doGetAuthorizationInfo方法获取当前用户的权限数据。
查看源码AuthorizingRealm的getAuthorizationInfo方法如下:
protected AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals)
if (principals == null)
return null;
AuthorizationInfo info = null;
if (log.isTraceEnabled())
log.trace("Retrieving AuthorizationInfo for principals [" + principals + "]");
Cache<Object, AuthorizationInfo> cache = getAvailableAuthorizationCache();
if (cache != null)
if (log.isTraceEnabled())
log.trace("Attempting to retrieve the AuthorizationInfo from cache.");
Object key = getAuthorizationCacheKey(principals);
info = cache.get(key);
if (log.isTraceEnabled())
if (info == null)
log.trace("No AuthorizationInfo found in cache for principals [" + principals + "]");
else
log.trace("AuthorizationInfo found in cache for principals [" + principals + "]");
if (info == null)
// Call template method if the info was not found in a cache
info = doGetAuthorizationInfo(principals);
// If the info is not null and the cache has been created, then cache the authorization info.
if (info != null && cache != null)
if (log.isTraceEnabled())
log.trace("Caching authorization info for principals: [" + principals + "].");
Object key = getAuthorizationCacheKey(principals);
cache.put(key, info);
return info;
发现:
Object key = getAuthorizationCacheKey(principals);
获取的key是principals的toString方法返回值,而SecurityUtils.getSubject().getPrincipal()方法每次返回的都是新的对象,所以key每次都是动态变化的。所以只要在AuthorizingRealm的实现类中复写getAuthorizationCacheKey方法,将其返回当前的sessionId即可:
protected Object getAuthorizationCacheKey(PrincipalCollection principals)
return WebUtil.REQUEST.get().getSession().getId();
WebUtil.REQUEST.get(),是获取当前的HttpServletRequest的,项目里封装的方法。
复写getAuthorizationCacheKey方法后,在getAuthorizationInfo方法中,同一个session就可以获取已经缓存起来的权限,不需要每次请求都调用一次doGetAuthorizationInfo方法了。不知道是不是还有其他更好的解决方案。
以上是关于SpringShiro每次请求的权限校验,都会调用一次doGetAuthorizationInfo的问题的主要内容,如果未能解决你的问题,请参考以下文章
SpringShiro每次请求的权限校验,都会调用一次doGetAuthorizationInfo的问题