Spring Security3.1 配置說明

原博文地址:http://blog.csdn.net/k10509806/article/details/6369131


一、數據庫結構

     先來看一下數據庫結構,採用的是基於角色-資源-用戶的權限管理設計。(MySql數據庫)

    爲了節省篇章,只對比較重要的字段進行註釋。

    1.用戶表Users

    CREATE TABLE `users` (

       -- 賬號是否有限 1. 是 0.否
       `enable` int(11) default NULL,
       `password` varchar(255) default NULL,
       `account` varchar(255) default NULL,
       `id` int(11) NOT NULL auto_increment,
       PRIMARY KEY  (`id`)
    )

 

   2.角色表Roles

   CREATE TABLE `roles` (
     `enable` int(11) default NULL,
     `name` varchar(255) default NULL,
     `id` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`id`)
   )

 

   3 用戶_角色表users_roles

   CREATE TABLE `users_roles` (

     --用戶表的外鍵
     `uid` int(11) default NULL,

     --角色表的外鍵
     `rid` int(11) default NULL,
     `urId` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`urId`),
     KEY `rid` (`rid`),
     KEY `uid` (`uid`),
    CONSTRAINT `users_roles_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`),
    CONSTRAINT `users_roles_ibfk_2` FOREIGN KEY (`uid`) REFERENCES `users` (`id`)
   )

 

   4.資源表resources

   CREATE TABLE `resources` (
     `memo` varchar(255) default NULL,

     -- 權限所對應的url地址
     `url` varchar(255) default NULL,

     --優先權
     `priority` int(11) default NULL,

     --類型
     `type` int(11) default NULL,

     --權限所對應的編碼,例201代表發表文章
     `name` varchar(255) default NULL,
     `id` int(11) NOT NULL auto_increment,
     PRIMARY KEY  (`id`)
   )

 

   5.角色_資源表roles_resources

    CREATE TABLE `roles_resources` (
      `rsid` int(11) default NULL,
      `rid` int(11) default NULL,
      `rrId` int(11) NOT NULL auto_increment,
      PRIMARY KEY  (`rrId`),
      KEY `rid` (`rid`),
      KEY `roles_resources_ibfk_2` (`rsid`),
      CONSTRAINT `roles_resources_ibfk_2` FOREIGN KEY (`rsid`) REFERENCES `resources` (`id`),
      CONSTRAINT `roles_resources_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `roles` (`id`)
      )

 

  二、系統配置

   所需要的jar包,請自行到官網下載,我用的是Spring Security3.1.0.RC1版的。把dist下的除了源碼件包導入就行了。還有那些零零碎的   數據庫驅動啊,log4j.jar等等,我相信在用Spring Security之前,大家已經會的了。

  1) web.xml

 

[xhtml] view plaincopy
  1. <!-- Spring -->  
  2.   <context-param>  
  3.     <param-name>contextConfigLocation</param-name>  
  4.     <param-value>classpath:applicationContext.xml,classpath:applicationContext-security.xml</param-value>  
  5.   </context-param>  
  6.     
  7.       
  8.   <listener>  
  9.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  10.   </listener>  
  11.   <!-- 權限 -->  
  12.   <filter>  
  13.         <filter-name>springSecurityFilterChain</filter-name>  
  14.         <filter-class>  
  15.             org.springframework.web.filter.DelegatingFilterProxy  
  16.         </filter-class>  
  17.    </filter>  
  18.     <filter-mapping>  
  19.         <filter-name>springSecurityFilterChain</filter-name>  
  20.         <url-pattern>/*</url-pattern>  
  21.     </filter-mapping>  

 這裏主要是配置了讓容器啓動的時候加載application-security.xml和Spring Security的權限過濾器代理,讓其過濾所有的客服請求。

 2)application-security.xml

 

[xhtml] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  3.     xmlns:beans="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  6.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
  7.                           
  8.     <global-method-security pre-post-annotations="enabled" />   
  9.     <!-- 該路徑下的資源不用過濾 -->             
  10.     <http pattern="/js/**" security="none"/>  
  11.     <http use-expressions="true" auto-config="true">  
  12.           
  13.         <form-login />  
  14.         <logout/>  
  15.         <!-- 實現免登陸驗證 -->  
  16.         <remember-me />  
  17.         <session-management invalid-session-url="/timeout.jsp">  
  18.             <concurrency-control max-sessions="10" error-if-maximum-exceeded="true" />  
  19.         </session-management>  
  20.         <custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/>  
  21.     </http>  
  22.     <!-- 配置過濾器 -->  
  23.     <beans:bean id="myFilter" class="com.huaxin.security.MySecurityFilter">  
  24.         <!-- 用戶擁有的權限 -->  
  25.         <beans:property name="authenticationManager" ref="myAuthenticationManager" />  
  26.         <!-- 用戶是否擁有所請求資源的權限 -->  
  27.         <beans:property name="accessDecisionManager" ref="myAccessDecisionManager" />  
  28.         <!-- 資源與權限對應關係 -->  
  29.         <beans:property name="securityMetadataSource" ref="mySecurityMetadataSource" />  
  30.     </beans:bean>  
  31.     <!-- 實現了UserDetailsService的Bean -->  
  32.     <authentication-manager alias="myAuthenticationManager">  
  33.         <authentication-provider user-service-ref="myUserDetailServiceImpl" />  
  34.     </authentication-manager>  
  35.     <beans:bean id="myAccessDecisionManager" class="com.huaxin.security.MyAccessDecisionManager"></beans:bean>  
  36.     <beans:bean id="mySecurityMetadataSource" class="com.huaxin.security.MySecurityMetadataSource">  
  37.         <beans:constructor-arg name="resourcesDao" ref="resourcesDao"></beans:constructor-arg>  
  38.     </beans:bean>  
  39.     <beans:bean id="myUserDetailServiceImpl" class="com.huaxin.security.MyUserDetailServiceImpl">  
  40.         <beans:property name="usersDao" ref="usersDao"></beans:property>  
  41.     </beans:bean>  
  42. </beans:beans>  

 

我們在第二個http標籤下配置一個我們自定義的繼承了org.springframework.security.access.intercept.AbstractSecurityInterceptor的Filter,並注入其

必須的3個組件authenticationManager、accessDecisionManager和securityMetadataSource。其作用上面已經註釋了。

 

<custom-filter ref="myFilter" before="FILTER_SECURITY_INTERCEPTOR"/> 這裏的FILTER_SECURITY_INTERCEPTOR是Spring Security默認的Filter,

我們自定義的Filter必須在它之前,過濾客服請求。接下來看下我們最主要的myFilter吧。

 

3)myFilter

  (1) MySecurityFilter.java 過濾用戶請求

 

[java] view plaincopy
  1. public class MySecurityFilter extends AbstractSecurityInterceptor implements Filter {  
  2.     //與applicationContext-security.xml裏的myFilter的屬性securityMetadataSource對應,  
  3.     //其他的兩個組件,已經在AbstractSecurityInterceptor定義  
  4.     private FilterInvocationSecurityMetadataSource securityMetadataSource;  
  5.   
  6.     @Override  
  7.     public SecurityMetadataSource obtainSecurityMetadataSource() {  
  8.         return this.securityMetadataSource;  
  9.     }  
  10.   
  11.     public void doFilter(ServletRequest request, ServletResponse response,  
  12.             FilterChain chain) throws IOException, ServletException {  
  13.         FilterInvocation fi = new FilterInvocation(request, response, chain);  
  14.         invoke(fi);  
  15.     }  
  16.       
  17.     private void invoke(FilterInvocation fi) throws IOException, ServletException {  
  18.         // object爲FilterInvocation對象  
  19.                   //super.beforeInvocation(fi);源碼  
  20.         //1.獲取請求資源的權限  
  21.         //執行Collection<ConfigAttribute> attributes = SecurityMetadataSource.getAttributes(object);  
  22.         //2.是否擁有權限  
  23.         //this.accessDecisionManager.decide(authenticated, object, attributes);  
  24.         InterceptorStatusToken token = super.beforeInvocation(fi);  
  25.         try {  
  26.             fi.getChain().doFilter(fi.getRequest(), fi.getResponse());  
  27.         } finally {  
  28.             super.afterInvocation(token, null);  
  29.         }  
  30.     }  
  31.   
  32.     public FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {  
  33.         return securityMetadataSource;  
  34.     }  
  35.   
  36.     public void setSecurityMetadataSource(FilterInvocationSecurityMetadataSource securityMetadataSource) {  
  37.         this.securityMetadataSource = securityMetadataSource;  
  38.     }  
  39.       
  40.     public void init(FilterConfig arg0) throws ServletException {  
  41.         // TODO Auto-generated method stub  
  42.     }  
  43.       
  44.     public void destroy() {  
  45.         // TODO Auto-generated method stub  
  46.           
  47.     }  
  48.   
  49.     @Override  
  50.     public Class<? extends Object> getSecureObjectClass() {  
  51.         //下面的MyAccessDecisionManager的supports方面必須放回true,否則會提醒類型錯誤  
  52.         return FilterInvocation.class;  
  53.     }  
  54. }  

  核心的InterceptorStatusToken token = super.beforeInvocation(fi);會調用我們定義的accessDecisionManager:decide(Object object)和securityMetadataSource

  :getAttributes(Object object)方法。

 

 (2)MySecurityMetadataSource.java

 

[java] view plaincopy
  1. //1 加載資源與權限的對應關係  
  2. public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {  
  3.     //由spring調用  
  4.     public MySecurityMetadataSource(ResourcesDao resourcesDao) {  
  5.         this.resourcesDao = resourcesDao;  
  6.         loadResourceDefine();  
  7.     }  
  8.   
  9.     private ResourcesDao resourcesDao;  
  10.     private static Map<String, Collection<ConfigAttribute>> resourceMap = null;  
  11.   
  12.     public ResourcesDao getResourcesDao() {  
  13.         return resourcesDao;  
  14.     }  
  15.   
  16.     public void setResourcesDao(ResourcesDao resourcesDao) {  
  17.         this.resourcesDao = resourcesDao;  
  18.     }  
  19.   
  20.     public Collection<ConfigAttribute> getAllConfigAttributes() {  
  21.         // TODO Auto-generated method stub  
  22.         return null;  
  23.     }  
  24.   
  25.     public boolean supports(Class<?> clazz) {  
  26.         // TODO Auto-generated method stub  
  27.         return true;  
  28.     }  
  29.     //加載所有資源與權限的關係  
  30.     private void loadResourceDefine() {  
  31.         if(resourceMap == null) {  
  32.             resourceMap = new HashMap<String, Collection<ConfigAttribute>>();  
  33.             List<Resources> resources = this.resourcesDao.findAll();  
  34.             for (Resources resource : resources) {  
  35.                 Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();  
  36.                                 //以權限名封裝爲Spring的security Object  
  37.                 ConfigAttribute configAttribute = new SecurityConfig(resource.getName());  
  38.                 configAttributes.add(configAttribute);  
  39.                 resourceMap.put(resource.getUrl(), configAttributes);  
  40.             }  
  41.         }  
  42.           
  43.         Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();  
  44.         Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();  
  45.           
  46.     }  
  47.     //返回所請求資源所需要的權限  
  48.     public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {  
  49.           
  50.         String requestUrl = ((FilterInvocation) object).getRequestUrl();  
  51.         System.out.println("requestUrl is " + requestUrl);  
  52.         if(resourceMap == null) {  
  53.             loadResourceDefine();  
  54.         }  
  55.         return resourceMap.get(requestUrl);  
  56.     }  
  57.   
  58. }  

 這裏的resourcesDao,熟悉Dao設計模式和Spring 注入的朋友應該看得明白。

 

(3)MyUserDetailServiceImpl.java

 

[java] view plaincopy
  1. public class MyUserDetailServiceImpl implements UserDetailsService {  
  2.       
  3.     private UsersDao usersDao;  
  4.     public UsersDao getUsersDao() {  
  5.         return usersDao;  
  6.     }  
  7.   
  8.     public void setUsersDao(UsersDao usersDao) {  
  9.         this.usersDao = usersDao;  
  10.     }  
  11.       
  12.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {  
  13.         System.out.println("username is " + username);  
  14.         Users users = this.usersDao.findByName(username);  
  15.         if(users == null) {  
  16.             throw new UsernameNotFoundException(username);  
  17.         }  
  18.         Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);  
  19.           
  20.         boolean enables = true;  
  21.         boolean accountNonExpired = true;  
  22.         boolean credentialsNonExpired = true;  
  23.         boolean accountNonLocked = true;  
  24.           
  25.         User userdetail = new User(users.getAccount(), users.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);  
  26.         return userdetail;  
  27.     }  
  28.       
  29.     //取得用戶的權限  
  30.     private Set<GrantedAuthority> obtionGrantedAuthorities(Users user) {  
  31.         Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
  32.         Set<Roles> roles = user.getRoles();  
  33.           
  34.         for(Roles role : roles) {  
  35.             Set<Resources> tempRes = role.getResources();  
  36.             for(Resources res : tempRes) {  
  37.                 authSet.add(new GrantedAuthorityImpl(res.getName()));  
  38. s           }  
  39.         }  
  40.         return authSet;  
  41.     }  
  42. }  

 

(4) MyAccessDecisionManager.java

[java] view plaincopy
  1. public class MyAccessDecisionManager implements AccessDecisionManager {  
  2.       
  3.     public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {  
  4.         if(configAttributes == null) {  
  5.             return;  
  6.         }  
  7.         //所請求的資源擁有的權限(一個資源對多個權限)  
  8.         Iterator<ConfigAttribute> iterator = configAttributes.iterator();  
  9.         while(iterator.hasNext()) {  
  10.             ConfigAttribute configAttribute = iterator.next();  
  11.             //訪問所請求資源所需要的權限  
  12.             String needPermission = configAttribute.getAttribute();  
  13.             System.out.println("needPermission is " + needPermission);  
  14.             //用戶所擁有的權限authentication  
  15.             for(GrantedAuthority ga : authentication.getAuthorities()) {  
  16.                 if(needPermission.equals(ga.getAuthority())) {  
  17.                     return;  
  18.                 }  
  19.             }  
  20.         }  
  21.         //沒有權限  
  22.         throw new AccessDeniedException(" 沒有權限訪問! ");  
  23.     }  
  24.   
  25.     public boolean supports(ConfigAttribute attribute) {  
  26.         // TODO Auto-generated method stub  
  27.         return true;  
  28.     }  
  29.   
  30.     public boolean supports(Class<?> clazz) {  
  31.         // TODO Auto-generated method stub  
  32.         return true;  
  33.     }  
  34.       
  35. }  

 

三、流程

 1)容器啓動(MySecurityMetadataSource:loadResourceDefine加載系統資源與權限列表)
 2)用戶發出請求
 3)過濾器攔截(MySecurityFilter:doFilter)
 4)取得請求資源所需權限(MySecurityMetadataSource:getAttributes)
 5)匹配用戶擁有權限和請求權限(MyAccessDecisionManager:decide),如果用戶沒有相應的權限,

     執行第6步,否則執行第7步。
 6)登錄
 7)驗證並授權(MyUserDetailServiceImpl:loadUserByUsername)
 8)重複4,5


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章