分享

shiro安全框架扩展教程--如何动态控制页面节点元素的权限

 WindySky 2018-02-09

         上些章节我们都学习了shiro中的各种实际应用技巧,今天我想讲的是如何动态控制页面节点权限,相信这个控制对于很多玩权限的人来说都是一个比较头痛的,

因为这实在不怎么好统一控制的,现在我来展示下我通过shiro是如何实现的,算是抛砖引玉,希望大家有更好的解决方案,可以相互学习;下面就直接进入主题不啰嗦了


之前我们已经学习了如何在项目启动的时候加载所有的资源角色,包括第三方资源,下面我再帖上加长加粗版的代码方便说明


  1. package com.silvery.security.shiro.service.impl;  
  2.   
  3. import java.text.MessageFormat;  
  4. import java.util.HashMap;  
  5. import java.util.HashSet;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import java.util.Set;  
  9.   
  10. import org.apache.shiro.cache.Cache;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12.   
  13. import com.silvery.project.cms.model.Authority;  
  14. import com.silvery.project.cms.model.Permission;  
  15. import com.silvery.project.cms.service.PermissionService;  
  16. import com.silvery.project.cms.vo.PermissionVo;  
  17. import com.silvery.security.shiro.cache.SimpleMapCache;  
  18. import com.silvery.security.shiro.cache.extend.SimpleCacheManager;  
  19. import com.silvery.security.variable.Const;  
  20.   
  21. /**  
  22.  *   
  23.  * 加载第三方角色资源配置服务类  
  24.  *   
  25.  * @author shadow  
  26.  *   
  27.  */  
  28. public class SimpleFilterChainDefinitionsService extends AbstractFilterChainDefinitionsService {  
  29.   
  30.     @Autowired  
  31.     private SimpleCacheManager simpleCacheManager;  
  32.   
  33.     @Autowired  
  34.     private PermissionService permissionService;  
  35.   
  36.     @Override  
  37.     public Map<String, String> initOtherPermission() {  
  38.         return converResultMap(initOperation());  
  39.     }  
  40.   
  41.     @SuppressWarnings("unchecked")  
  42.     private Map<Object, Object> initOperation() {  
  43.   
  44.         Map<Object, Object> resultMap = new HashMap<Object, Object>();  
  45.   
  46.         // 加载数据库所有资源  
  47.         PermissionVo vo = new PermissionVo();  
  48.         List<Permission> permissions = (List<Permission>) permissionService.query(vo).getValue();  
  49.   
  50.         List<Authority> authorities = null;  
  51.   
  52.         for (Permission permission : permissions) {  
  53.   
  54.             // 遍历查询当前资源的配置角色  
  55.             vo.setId(permission.getId());  
  56.             authorities = (List<Authority>) permissionService.query4authority(vo).getValue();  
  57.   
  58.             // 组装角色集合  
  59.             Set<String> authoritySet = getPermissionSet(authorities);  
  60.   
  61.             if (authoritySet.isEmpty()) {  
  62.                 continue;  
  63.             }  
  64.             if (permission.getType() == 1) {  
  65.                 // 请求路径资源处理  
  66.                 resultMap.put(permission.getContent(), MessageFormat.format(SHIRO_AUTHORITY_FORMAT, authoritySet));  
  67.             } else {  
  68.                 // 元素资源处理  
  69.                 Map<Object, Object> map = new HashMap<Object, Object>(1);  
  70.                 map.put(Const.OTHER_PERMISSSION_CACHE_NAME, authoritySet);  
  71.                 Cache<Object, Object> cache = new SimpleMapCache(Const.OTHER_PERMISSSION_CACHE_NAME, map);  
  72.                 simpleCacheManager.createCache(Const.OTHER_PERMISSSION_CACHE_NAME + "_" + permission.getId(), cache);  
  73.             }  
  74.         }  
  75.   
  76.         return resultMap;  
  77.     }  
  78.   
  79.     /** 获取角色名称集合 */  
  80.     private Set<String> getPermissionSet(List<Authority> authorities) {  
  81.         Set<String> authoritieSet = new HashSet<String>(authorities.size());  
  82.         for (Authority authority : authorities) {  
  83.             authoritieSet.add(authority.getContent());  
  84.         }  
  85.         return authoritieSet;  
  86.     }  
  87.   
  88.     /** 泛型Object转换String */  
  89.     private Map<String, String> converResultMap(Map<Object, Object> map) {  
  90.         Map<String, String> resultMap = new HashMap<String, String>(map.size());  
  91.         for (Map.Entry<Object, Object> entry : map.entrySet()) {  
  92.             resultMap.put(entry.getKey().toString(), entry.getValue().toString());  
  93.         }  
  94.         return resultMap;  
  95.     }  
  96.   
  97. }  

1. 加载所有资源,包括请求URL,元素节点等数据,我这里为了演示,没有分那么细就只有两种

2. 请求URL的直接放到框架中,形式如/user/list.do*=role[root,user],跟我们shiro.xml配置的一样

3. 元素节点则相应放到以键值对的形式放到缓存,以节点的编号组合成key保证可以找到这个缓存对,值是相应的角色集合


我们的缓存就存在各个资源所需要的角色集合, 加载数据步骤已经完毕了下面看看我们是怎么应用的


首先我是使用springMVC+freemarker作为展现层,具体怎么配置整合我也不说,百度一堆,直接看我帖代码说明


  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www./TR/xhtml1/DTD/xhtml1-strict.dtd">  
  2. <html xmlns="http://www./1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>欢迎主页</title>  
  6. </head>  
  7. <body>  
  8.     ${username!"游客"}, 欢迎您的访问! <br />  
  9.     <hr />  
  10.     可选操作:  
  11.     <#if username??>  
  12.         <@sec id="2" body="<a href='/cms/user/page.do'>用户列表</a> " /><a href="/cms/authority/page.do">权限列表</a> <a href="/cms/permission/page.do">资源列表</a> <a href="/cms/logout.do">注销退出</a>   
  13.     <#else>  
  14.         <a href="#" onclick="top.location.href='/cms/logout.do';">前往登录</a>   
  15.     </#if>  
  16.     <hr />  
  17. </body>  
  18. </html>  

很明显看到我的页面有一个@sec的标签,然后有两个参数,一个id,一个是body,至于id则是你资源的编号,body是需要元素节点内容


然后我们怎么通过这个标签来判定是否在页面渲染body的节点内容呢?


下面我们看看这个@sec的实现


  1. package com.silvery.core.freemarker;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Map;  
  5. import java.util.Set;  
  6.   
  7. import org.apache.shiro.SecurityUtils;  
  8. import org.apache.shiro.cache.Cache;  
  9. import org.apache.shiro.subject.Subject;  
  10. import org.springframework.beans.factory.annotation.Autowired;  
  11.   
  12. import com.silvery.security.shiro.cache.extend.SimpleCacheManager;  
  13. import com.silvery.security.variable.Const;  
  14.   
  15. import freemarker.core.Environment;  
  16. import freemarker.template.TemplateDirectiveBody;  
  17. import freemarker.template.TemplateDirectiveModel;  
  18. import freemarker.template.TemplateException;  
  19. import freemarker.template.TemplateModel;  
  20.   
  21. /**  
  22.  *   
  23.  * FreeMarker自定义标签,节点权限控制  
  24.  *   
  25.  * @author shadow  
  26.  *   
  27.  */  
  28. public class SecurityTag implements TemplateDirectiveModel {  
  29.   
  30.     @Autowired  
  31.     private SimpleCacheManager simpleCacheManager;  
  32.   
  33.     @SuppressWarnings("unchecked")  
  34.     public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody directiveBody)  
  35.             throws TemplateException, IOException {  
  36.   
  37.         Object id = params.get("id");  
  38.         Object body = params.get("body");  
  39.   
  40.         validate(id, body);  
  41.   
  42.         if (hasRole(id)) {  
  43.             env.getOut().write(body.toString());  
  44.         } else {  
  45.             env.getOut().write("");  
  46.         }  
  47.   
  48.     }  
  49.   
  50.     private void validate(Object id, Object body) throws TemplateException {  
  51.         if (id == null || id.toString().trim().equals("")) {  
  52.             throw new TemplateException("参数[id]不能为空", null);  
  53.         }  
  54.         if (body == null) {  
  55.             throw new TemplateException("参数[body]不能为空", null);  
  56.         }  
  57.     }  
  58.   
  59.     @SuppressWarnings("unchecked")  
  60.     private boolean hasRole(Object id) {  
  61.         Cache<Object, Object> cache = simpleCacheManager.getCache(Const.OTHER_PERMISSSION_CACHE_NAME + "_" + id);  
  62.         if (cache == null) {  
  63.             return false;  
  64.         } else {  
  65.             Object obj = cache.get(Const.OTHER_PERMISSSION_CACHE_NAME);  
  66.             if (obj == null) {  
  67.                 return false;  
  68.             }  
  69.             Set<String> authoritySet = (Set<String>) obj;  
  70.             Subject subject = SecurityUtils.getSubject();  
  71.             for (String authority : authoritySet) {  
  72.                 if (subject.hasRole(authority)) {  
  73.                     return true;  
  74.                 }  
  75.             }  
  76.         }  
  77.         return false;  
  78.     }  
  79.   
  80. }  

很清晰地看到,我们是用到之前的那个资源角色缓存,通过判定缓存中存在的角色与当前shiro认证用户拥有的角色匹配,如存在任意相同角色则渲染相应节点


如Subject拥有角色[root,user],而x编号资源拥有[user,test]角色,很明显有交集会认证通过,反之则直接渲染空字符


大概流程就是这样,有的人可能会问,如何配置这个tag实现类呢?我帖下spring-mvc.xml的freemarker配置


  1. <!-- FreeMarker配置 -->  
  2.     <bean id="freemarkerConfig"  
  3.         class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  4.         <property name="templateLoaderPath" value="/WEB-INF/ftl/" />  
  5.         <property name="defaultEncoding" value="UTF-8" />  
  6.         <property name="freemarkerVariables">  
  7.             <map>  
  8.                 <entry key="sec">  
  9.                     <bean class="com.silvery.core.freemarker.SecurityTag">  
  10.                     </bean>  
  11.                 </entry>  
  12.             </map>  
  13.         </property>  
  14.         <property name="freemarkerSettings">  
  15.             <props>  
  16.                 <prop key="template_update_delay">10</prop>  
  17.                 <prop key="locale">zh_CN</prop>  
  18.                 <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>  
  19.                 <prop key="date_format">yyyy-MM-dd</prop>  
  20.                 <prop key="number_format">#.####</prop>  
  21.             </props>  
  22.         </property>  
  23.     </bean>  

相信懂freemarker的人都能看明白,我也不累赘说明;最后再说一句,谢谢大家支持.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多