Spring Security教程(11)---- 使用数据库来管理资源

这个可以说是SpringSecurity最核心的东西,在项目中资源很多肯定不能一一配置到配置文件中,所以用数据库来管理资源是必然的。这个也很容易实现。表结构已经在之前都创建过了。

首先我们要来从数据库中获取到资源与权限的对应列表,这个在dao层实现即可需要获取到url地址和AUTH_**这种权限标识,注意:不是权限ID和资源ID。

  1. public List<Map<String,String>> getURLResourceMapping(){  
  2.     String sql = "SELECT S3.RESOURCE_PATH,S2.AUTHORITY_MARK FROM SYS_AUTHORITIES_RESOURCES S1 "+  
  3.             "JOIN SYS_AUTHORITIES S2 ON S1.AUTHORITY_ID = S2.AUTHORITY_ID "+  
  4.             "JOIN SYS_RESOURCES S3 ON S1.RESOURCE_ID = S3.RESOURCE_ID S3.RESOURCE_TYPE='URL' ORDER BY S3.PRIORITY DESC";  
  5.       
  6.     List<Map<String,String>> list = new ArrayList<Map<String,String>>();  
  7.       
  8.     Query query = this.entityManager.createNativeQuery(sql);  
  9.     List<Object[]> result = query.getResultList();  
  10.     Iterator<Object[]> it = result.iterator();  
  11.       
  12.     while(it.hasNext()){  
  13.         Object[] o = it.next();  
  14.         Map<String,String> map = new HashMap<String,String>();  
  15.         map.put("resourcePath", (String)o[0]);  
  16.         map.put("authorityMark", (String)o[1]);  
  17.         list.add(map);  
  18.     }  
  19.       
  20.     return list;  
  21. }  
创建SecurityMetadataSource供过滤器使用,SecurityMetadataSource需要实现FilterInvocationSecurityMetadataSource
  1. public class URLFilterInvocationSecurityMetadataSource implements  
  2.         FilterInvocationSecurityMetadataSource,InitializingBean {  
  3.   
  4.     protected final Log logger = LogFactory.getLog(getClass());  
  5.       
  6.     private final static List<ConfigAttribute> NULL_CONFIG_ATTRIBUTE = Collections.emptyList();  
  7.     //权限集合  
  8.     private Map<RequestMatcher, Collection<ConfigAttribute>> requestMap;  
  9.       
  10.     @Autowired  
  11.     private SysResourceRepository sysResourceRepository;  
  12.       
  13.     /* (non-Javadoc) 
  14.      * @see org.springframework.security.access.SecurityMetadataSource#getAttributes(java.lang.Object) 
  15.      */  
  16.     @Override  
  17.     public Collection<ConfigAttribute> getAttributes(Object object)  
  18.             throws IllegalArgumentException {  
  19.         final HttpServletRequest request = ((FilterInvocation) object).getRequest();  
  20.           
  21.         Collection<ConfigAttribute> attrs = NULL_CONFIG_ATTRIBUTE;  
  22.           
  23.         for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) {  
  24.             if (entry.getKey().matches(request)) {  
  25.                 attrs =  entry.getValue();  
  26.                 break;  
  27.             }  
  28.         }  
  29.         logger.info("URL资源:"+request.getRequestURI()+ " -> " + attrs);  
  30.         return attrs;  
  31.     }  
  32.   
  33.     /* (non-Javadoc) 
  34.      * @see org.springframework.security.access.SecurityMetadataSource#getAllConfigAttributes() 
  35.      */  
  36.     @Override  
  37.     public Collection<ConfigAttribute> getAllConfigAttributes() {  
  38.         Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>();  
  39.   
  40.         for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : requestMap.entrySet()) {  
  41.             allAttributes.addAll(entry.getValue());  
  42.         }  
  43.   
  44.         return allAttributes;  
  45.     }  
  46.   
  47.     /* (non-Javadoc) 
  48.      * @see org.springframework.security.access.SecurityMetadataSource#supports(java.lang.Class) 
  49.      */  
  50.     @Override  
  51.     public boolean supports(Class<?> clazz) {  
  52.         return FilterInvocation.class.isAssignableFrom(clazz);  
  53.     }  
  54.       
  55.     private Map<String,String> loadResuorce(){  
  56.         Map<String,String> map = new LinkedHashMap<String,String>();  
  57.           
  58.         List<Map<String,String>> list = this.sysResourceRepository.getURLResourceMapping();  
  59.         Iterator<Map<String,String>> it = list.iterator();  
  60.         while(it.hasNext()){  
  61.             Map<String,String> rs = it.next();  
  62.             String resourcePath = rs.get("resourcePath");  
  63.             String authorityMark = rs.get("authorityMark");  
  64.               
  65.             if(map.containsKey(resourcePath)){  
  66.                 String mark = map.get("resourcePath");  
  67.                 map.put(resourcePath, mark+","+authorityMark);  
  68.             }else{  
  69.                 map.put(resourcePath, authorityMark);  
  70.             }  
  71.         }  
  72.         return map;  
  73.     }  
  74.       
  75.     protected Map<RequestMatcher, Collection<ConfigAttribute>> bindRequestMap(){  
  76.         Map<RequestMatcher, Collection<ConfigAttribute>> map =   
  77.                 new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();  
  78.           
  79.         Map<String,String> resMap = this.loadResuorce();  
  80.         for(Map.Entry<String,String> entry:resMap.entrySet()){  
  81.             String key = entry.getKey();  
  82.             Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();  
  83.             atts = SecurityConfig.createListFromCommaDelimitedString(entry.getValue());  
  84.             map.put(new AntPathRequestMatcher(key), atts);  
  85.         }  
  86.           
  87.         return map;  
  88.     }  
  89.   
  90.     /* (non-Javadoc) 
  91.      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() 
  92.      */  
  93.     @Override  
  94.     public void afterPropertiesSet() throws Exception {  
  95.         this.requestMap = this.bindRequestMap();  
  96.         logger.info("资源权限列表"+this.requestMap);  
  97.     }  
  98.       
  99.     public void refreshResuorceMap(){  
  100.         this.requestMap = this.bindRequestMap();  
  101.     }  
  102.   
  103. }  
bindRequestMap需要在类初始化的时候就完成,但是这个不能写在构造函数中,因为构造函数执行是SysResourceRepository还没有注入过来。所以就通过实现InitializingBean把初始化操作放在afterPropertiesSet方法中。

getAllConfigAttributes:获取所有权限集合

getAttributes:根据request请求获取访问资源所需权限

代码很简单,很容易看懂,就不再多做解释,下面看配置文件

  1. <sec:http auto-config="true" access-decision-manager-ref="accessDecisionManager">  
  2.       
  3.     <sec:access-denied-handler ref="accessDeniedHandler"/>  
  4.       
  5.     <sec:session-management invalid-session-url="/login.jsp" />  
  6.       
  7.     <sec:form-login login-page="/login.jsp"  
  8.         login-processing-url="/login.do"  
  9.         authentication-failure-url="/login.jsp"  
  10.         authentication-success-handler-ref="authenticationSuccessHandler"  
  11.     />  
  12.       
  13.     <sec:custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>  
  14.           
  15. </sec:http>  
  16.   
  17. <bean id="filterSecurityInterceptor" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">  
  18.     <property name="accessDecisionManager" ref="accessDecisionManager" />  
  19.     <property name="authenticationManager" ref="authenticationManager" />  
  20.     <property name="securityMetadataSource" ref="securityMetadataSource" />  
  21. </bean>  
  22.   
  23. <bean id="securityMetadataSource"  
  24.     class="com.zrhis.system.security.URLFilterInvocationSecurityMetadataSource"/>  

通过配置custom-filter来增加过滤器,before="FILTER_SECURITY_INTERCEPTOR"表示在SpringSecurity默认的过滤器之前执行。

FilterSecurityInterceptor还用SpringSecurity默认的就可以了,这个是没有必要自己写的只要在SecurityMetadataSource处理好资源与权限的对应关系就可以了。

到此为止SpringSecurity框架已基本完善,可以说在项目中用已经没什么问题了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值