注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

无线时代辐射无穷

抓紧生宝宝,小心辐射

 
 
 

日志

 
 

Spring Security 2 配置精讲(2)  

2009-12-29 16:14:54|  分类: springsecurity |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

使用数据库对资源进行管理

在完成了使用数据库来进行用户和权限的管理之后,我们再来看看http配置的部分。在实际应用中,我们不可能使用类似/**的方式来指定URL与权限ROLE的对应关系,而是会针对某些URL,指定某些特定的ROLE。而URL与ROLE之间的映射关系最好可以进行扩展和配置。而URL属于资源的一种,所以接下来,我们就来看看如何使用数据库来对权限和资源的匹配关系进行管理,并且将认证匹配加入到Spring Security中去。

权限和资源的设计

上面我们讲到,用户(User)和权限(Role)之间是一个多对多的关系。那么权限(Role)和资源(Resource)之间呢?其实他们之间也是一个典型的多对多的关系,我们同样用3张表来表示:

Java代码 复制代码
  1. CREATE TABLE `role` (   
  2.   `id` int(11) NOT NULL auto_increment,   
  3.   `name` varchar(255default NULL,   
  4.   `description` varchar(255default NULL,   
  5.   PRIMARY KEY  (`id`)   
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
  7.   
  8. CREATE TABLE `resource` (   
  9.   `id` int(11) NOT NULL auto_increment,   
  10.   `type` varchar(255default NULL,   
  11.   `value` varchar(255default NULL,   
  12.   PRIMARY KEY  (`id`)   
  13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;   
  14.   
  15. CREATE TABLE `role_resource` (   
  16.   `role_id` int(11) NOT NULL,   
  17.   `resource_id` int(11) NOT NULL,   
  18.   PRIMARY KEY  (`role_id`,`resource_id`),   
  19.   KEY `FKAEE599B751827FA1` (`role_id`),   
  20.   KEY `FKAEE599B7EFD18D21` (`resource_id`),   
  21.   CONSTRAINT `FKAEE599B751827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),   
  22.   CONSTRAINT `FKAEE599B7EFD18D21` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`id`)   
  23. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
CREATE TABLE `role` (    `id` int(11) NOT NULL auto_increment,    `name` varchar(255) default NULL,    `description` varchar(255) default NULL,    PRIMARY KEY  (`id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;    CREATE TABLE `resource` (    `id` int(11) NOT NULL auto_increment,    `type` varchar(255) default NULL,    `value` varchar(255) default NULL,    PRIMARY KEY  (`id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;    CREATE TABLE `role_resource` (    `role_id` int(11) NOT NULL,    `resource_id` int(11) NOT NULL,    PRIMARY KEY  (`role_id`,`resource_id`),    KEY `FKAEE599B751827FA1` (`role_id`),    KEY `FKAEE599B7EFD18D21` (`resource_id`),    CONSTRAINT `FKAEE599B751827FA1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`),    CONSTRAINT `FKAEE599B7EFD18D21` FOREIGN KEY (`resource_id`) REFERENCES `resource` (`id`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;



在这里Resource可能分成多种类型,比如MENU,URL,METHOD等等。

针对资源的认证

针对资源的认证,实际上应该由Spring Security中的FilterSecurityInterceptor这个过滤器来完成。不过内置的FilterSecurityInterceptor的实现往往无法满足我们的要求,所以传统的Acegi的方式,我们往往会替换FilterSecurityInterceptor的实现,从而对URL等资源进行认证。

不过在Spring Security中,由于默认的拦截器链内置了FilterSecurityInterceptor,而且上面我们也提到过,这个实现无法被替换。这就使我们犯了难。我们如何对资源进行认证呢?

实际上,我们虽然无法替换FilterSecurityInterceptor的默认实现,不过我们可以再实现一个类似的过滤器,并将我们自己的过滤器作为一个customer-filter,加到默认的过滤器链的最后,从而完成整个过滤检查。

接下来我们就来看看一个完整的例子:

1. 建立权限(Role)和资源(Resource)之间的关联关系

修改上面的权限(Role)的Entity定义:

Java代码 复制代码
  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
  3. public class Role {   
  4.        
  5.     @Id  
  6.     @GeneratedValue  
  7.     private Integer id;   
  8.        
  9.     private String name;   
  10.        
  11.     @ManyToMany(targetEntity = Resource.class, fetch = FetchType.EAGER)   
  12.     @JoinTable(name = "role_resource", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "resource_id"))   
  13.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
  14.     private Set<Resource> resources;   
  15.   
  16.         // setters and getter   
  17. }  
@Entity  @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)  public class Role {      @Id   @GeneratedValue   private Integer id;      private String name;      @ManyToMany(targetEntity = Resource.class, fetch = FetchType.EAGER)      @JoinTable(name = "role_resource", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "resource_id"))      @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   private Set<Resource> resources;            // setters and getter  }  



增加资源(Resource)的Entity定义:

Java代码 复制代码
  1. @Entity  
  2. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
  3.   
  4. public class Resource {   
  5.   
  6.     @Id  
  7.     @GeneratedValue  
  8.     private Integer id;   
  9.        
  10.     private String type;   
  11.        
  12.     private String value;   
  13.        
  14.     @ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER)   
  15.     @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
  16.     private Set<Role> roles;   
  17.        
  18.     /**  
  19.      * The default constructor  
  20.      */  
  21.     public Resource() {   
  22.            
  23.     }   
  24. }  
@Entity  @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)    public class Resource {     @Id      @GeneratedValue   private Integer id;      private String type;      private String value;      @ManyToMany(mappedBy = "resources", targetEntity = Role.class, fetch = FetchType.EAGER)      @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   private Set<Role> roles;      /**    * The default constructor    */   public Resource() {       }  }



注意他们之间的多对多关系,以及他们之间关联关系的缓存和lazy属性设置。

2. 在系统启动的时候,把所有的资源load到内存作为缓存

由于资源信息对于每个项目来说,相对固定,所以我们可以将他们在系统启动的时候就load到内存作为缓存。这里做法很多,我给出的示例是将资源的存放在servletContext中。

Java代码 复制代码
  1. public class ServletContextLoaderListener implements ServletContextListener {   
  2.   
  3.     /* (non-Javadoc)  
  4.      * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)  
  5.      */  
  6.     public void contextInitialized(ServletContextEvent servletContextEvent) {   
  7.         ServletContext servletContext = servletContextEvent.getServletContext();   
  8.         SecurityManager securityManager = this.getSecurityManager(servletContext);   
  9.            
  10.         Map<String, String> urlAuthorities = securityManager.loadUrlAuthorities();   
  11.         servletContext.setAttribute("urlAuthorities", urlAuthorities);   
  12.     }   
  13.   
  14.        
  15.     /* (non-Javadoc)  
  16.      * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)  
  17.      */  
  18.     public void contextDestroyed(ServletContextEvent servletContextEvent) {   
  19.         servletContextEvent.getServletContext().removeAttribute("urlAuthorities");   
  20.     }   
  21.   
  22.     /**  
  23.      * Get SecurityManager from ApplicationContext  
  24.      *   
  25.      * @param servletContext  
  26.      * @return  
  27.      */  
  28.     protected SecurityManager getSecurityManager(ServletContext servletContext) {   
  29.        return (SecurityManager) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager");    
  30.     }   
  31.   
  32. }  
public class ServletContextLoaderListener implements ServletContextListener {        /* (non-Javadoc)       * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)       */      public void contextInitialized(ServletContextEvent servletContextEvent) {          ServletContext servletContext = servletContextEvent.getServletContext();          SecurityManager securityManager = this.getSecurityManager(servletContext);                    Map<String, String> urlAuthorities = securityManager.loadUrlAuthorities();          servletContext.setAttribute("urlAuthorities", urlAuthorities);      }              /* (non-Javadoc)       * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)       */      public void contextDestroyed(ServletContextEvent servletContextEvent) {          servletContextEvent.getServletContext().removeAttribute("urlAuthorities");      }        /**       * Get SecurityManager from ApplicationContext       *        * @param servletContext       * @return       */      protected SecurityManager getSecurityManager(ServletContext servletContext) {         return (SecurityManager) WebApplicationContextUtils.getWebApplicationContext(servletContext).getBean("securityManager");       }    }



这里,我们看到了SecurityManager,这是一个接口,用于权限相关的逻辑处理。还记得之前我们使用数据库管理User的时候所使用的一个实现类SecurityManagerSupport嘛?我们不妨依然借用这个类,让它实现SecurityManager接口,来同时完成url的读取工作。

Java代码 复制代码
  1. @Service("securityManager")   
  2. public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService, SecurityManager {   
  3.        
  4.     /**  
  5.      * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject  
  6.      *    
  7.      * @param sessionFactory  
  8.      */  
  9.     @Autowired  
  10.     public void init(SessionFactory sessionFactory) {   
  11.         super.setSessionFactory(sessionFactory);   
  12.     }   
  13.        
  14.     /* (non-Javadoc)  
  15.      * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)  
  16.      */  
  17.     public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {   
  18.         List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);   
  19.         if(users.isEmpty()) {   
  20.             throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");   
  21.         }   
  22.         return users.get(0);   
  23.     }   
  24.        
  25.     /* (non-Javadoc)  
  26.      * @see com.javaeye.sample.security.SecurityManager#loadUrlAuthorities()  
  27.      */  
  28.     public Map<String, String> loadUrlAuthorities() {   
  29.         Map<String, String> urlAuthorities = new HashMap<String, String>();   
  30.         List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?""URL");   
  31.         for(Resource resource : urlResources) {   
  32.             urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());   
  33.         }   
  34.         return urlAuthorities;   
  35.     }      
  36. }  
@Service("securityManager")  public class SecurityManagerSupport extends HibernateDaoSupport implements UserDetailsService, SecurityManager {            /**       * Init sessionFactory here because the annotation of Spring 2.5 can not support override inject       *         * @param sessionFactory       */      @Autowired      public void init(SessionFactory sessionFactory) {          super.setSessionFactory(sessionFactory);      }            /* (non-Javadoc)       * @see org.springframework.security.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)       */      public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {          List<User> users = getHibernateTemplate().find("FROM User user WHERE user.name = ? AND user.disabled = false", userName);          if(users.isEmpty()) {              throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");          }          return users.get(0);      }            /* (non-Javadoc)       * @see com.javaeye.sample.security.SecurityManager#loadUrlAuthorities()       */      public Map<String, String> loadUrlAuthorities() {          Map<String, String> urlAuthorities = new HashMap<String, String>();          List<Resource> urlResources = getHibernateTemplate().find("FROM Resource resource WHERE resource.type = ?", "URL");          for(Resource resource : urlResources) {              urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());          }          return urlAuthorities;      }     }  



3. 编写自己的FilterInvocationDefinitionSource实现类,对资源进行认证

Java代码 复制代码
  1. public class SecureResourceFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource, InitializingBean {   
  2.        
  3.     private UrlMatcher urlMatcher;   
  4.   
  5.     private boolean useAntPath = true;   
  6.        
  7.     private boolean lowercaseComparisons = true;   
  8.        
  9.     /**  
  10.      * @param useAntPath the useAntPath to set  
  11.      */  
  12.     public void setUseAntPath(boolean useAntPath) {   
  13.         this.useAntPath = useAntPath;   
  14.     }   
  15.        
  16.     /**  
  17.      * @param lowercaseComparisons  
  18.      */  
  19.     public void setLowercaseComparisons(boolean lowercaseComparisons) {   
  20.         this.lowercaseComparisons = lowercaseComparisons;   
  21.     }   
  22.        
  23.     /* (non-Javadoc)  
  24.      * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()  
  25.      */  
  26.     public void afterPropertiesSet() throws Exception {   
  27.            
  28.         // default url matcher will be RegexUrlPathMatcher   
  29.         this.urlMatcher = new RegexUrlPathMatcher();   
  30.            
  31.         if (useAntPath) {  // change the implementation if required   
  32.             this.urlMatcher = new AntUrlPathMatcher();   
  33.         }   
  34.            
  35.         // Only change from the defaults if the attribute has been set   
  36.         if ("true".equals(lowercaseComparisons)) {   
  37.             if (!this.useAntPath) {   
  38.                 ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true);   
  39.             }   
  40.         } else if ("false".equals(lowercaseComparisons)) {   
  41.             if (this.useAntPath) {   
  42.                 ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false);   
  43.             }   
  44.         }   
  45.            
  46.     }   
  47.        
  48.     /* (non-Javadoc)  
  49.      * @see org.springframework.security.intercept.ObjectDefinitionSource#getAttributes(java.lang.Object)  
  50.      */  
  51.     public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException {   
  52.            
  53.         FilterInvocation filterInvocation = (FilterInvocation) filter;   
  54.         String requestURI = filterInvocation.getRequestUrl();   
  55.         Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation);   
  56.            
  57.         String grantedAuthorities = null;   
  58.         for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) {   
  59.             Map.Entry<String, String> entry = iter.next();   
  60.             String url = entry.getKey();   
  61.                
  62.             if(urlMatcher.pathMatchesUrl(url, requestURI)) {   
  63.                 grantedAuthorities = entry.getValue();   
  64.                 break;   
  65.             }   
  66.                
  67.         }   
  68.            
  69.         if(grantedAuthorities != null) {   
  70.             ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();   
  71.             configAttrEditor.setAsText(grantedAuthorities);   
  72.             return (ConfigAttributeDefinition) configAttrEditor.getValue();   
  73.         }   
  74.            
  75.         return null;   
  76.     }   
  77.   
  78.     /* (non-Javadoc)  
  79.      * @see org.springframework.security.intercept.ObjectDefinitionSource#getConfigAttributeDefinitions()  
  80.      */  
  81.     @SuppressWarnings("unchecked")   
  82.     public Collection getConfigAttributeDefinitions() {   
  83.         return null;   
  84.     }   
  85.   
  86.     /* (non-Javadoc)  
  87.      * @see org.springframework.security.intercept.ObjectDefinitionSource#supports(java.lang.Class)  
  88.      */  
  89.     @SuppressWarnings("unchecked")   
  90.     public boolean supports(Class clazz) {   
  91.         return true;   
  92.     }   
  93.        
  94.     /**  
  95.      *   
  96.      * @param filterInvocation  
  97.      * @return  
  98.      */  
  99.     @SuppressWarnings("unchecked")   
  100.     private Map<String, String> getUrlAuthorities(FilterInvocation filterInvocation) {   
  101.         ServletContext servletContext = filterInvocation.getHttpRequest().getSession().getServletContext();   
  102.         return (Map<String, String>)servletContext.getAttribute("urlAuthorities");   
  103.     }   
  104.   
  105. }  
public class SecureResourceFilterInvocationDefinitionSource implements FilterInvocationDefinitionSource, InitializingBean {            private UrlMatcher urlMatcher;        private boolean useAntPath = true;            private boolean lowercaseComparisons = true;            /**       * @param useAntPath the useAntPath to set       */      public void setUseAntPath(boolean useAntPath) {          this.useAntPath = useAntPath;      }            /**       * @param lowercaseComparisons       */      public void setLowercaseComparisons(boolean lowercaseComparisons) {          this.lowercaseComparisons = lowercaseComparisons;      }            /* (non-Javadoc)       * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()       */      public void afterPropertiesSet() throws Exception {                    // default url matcher will be RegexUrlPathMatcher          this.urlMatcher = new RegexUrlPathMatcher();                    if (useAntPath) {  // change the implementation if required              this.urlMatcher = new AntUrlPathMatcher();          }                    // Only change from the defaults if the attribute has been set          if ("true".equals(lowercaseComparisons)) {              if (!this.useAntPath) {                  ((RegexUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(true);              }          } else if ("false".equals(lowercaseComparisons)) {              if (this.useAntPath) {                  ((AntUrlPathMatcher) this.urlMatcher).setRequiresLowerCaseUrl(false);              }          }                }            /* (non-Javadoc)       * @see org.springframework.security.intercept.ObjectDefinitionSource#getAttributes(java.lang.Object)       */      public ConfigAttributeDefinition getAttributes(Object filter) throws IllegalArgumentException {                    FilterInvocation filterInvocation = (FilterInvocation) filter;          String requestURI = filterInvocation.getRequestUrl();          Map<String, String> urlAuthorities = this.getUrlAuthorities(filterInvocation);                    String grantedAuthorities = null;          for(Iterator<Map.Entry<String, String>> iter = urlAuthorities.entrySet().iterator(); iter.hasNext();) {              Map.Entry<String, String> entry = iter.next();              String url = entry.getKey();                            if(urlMatcher.pathMatchesUrl(url, requestURI)) {                  grantedAuthorities = entry.getValue();                  break;              }                        }                    if(grantedAuthorities != null) {              ConfigAttributeEditor configAttrEditor = new ConfigAttributeEditor();              configAttrEditor.setAsText(grantedAuthorities);              return (ConfigAttributeDefinition) configAttrEditor.getValue();          }                    return null;      }        /* (non-Javadoc)       * @see org.springframework.security.intercept.ObjectDefinitionSource#getConfigAttributeDefinitions()       */      @SuppressWarnings("unchecked")   public Collection getConfigAttributeDefinitions() {          return null;      }        /* (non-Javadoc)       * @see org.springframework.security.intercept.ObjectDefinitionSource#supports(java.lang.Class)       */      @SuppressWarnings("unchecked")   public boolean supports(Class clazz) {          return true;      }            /**       *        * @param filterInvocation       * @return       */      @SuppressWarnings("unchecked")   private Map<String, String> getUrlAuthorities(FilterInvocation filterInvocation) {          ServletContext servletContext = filterInvocation.getHttpRequest().getSession().getServletContext();          return (Map<String, String>)servletContext.getAttribute("urlAuthorities");      }    }  



4. 配置文件修改

接下来,我们来修改一下Spring Security的配置文件,把我们自定义的这个过滤器插入到过滤器链中去。

Xml代码 复制代码
  1. <beans:beans xmlns="http://www.springframework.org/schema/security"  
  2.     xmlns:beans="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
  5.                         http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">  
  6.        
  7.     <beans:bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener" />  
  8.        
  9.     <http access-denied-page="/403.jsp" >  
  10.         <intercept-url pattern="/static/**" filters="none" />  
  11.         <intercept-url pattern="/template/**" filters="none" />  
  12.         <intercept-url pattern="/" filters="none" />  
  13.         <intercept-url pattern="/login.jsp" filters="none" />  
  14.         <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" />  
  15.         <logout logout-success-url="/login.jsp"/>  
  16.         <http-basic />  
  17.     </http>  
  18.   
  19.     <authentication-manager alias="authenticationManager"/>  
  20.        
  21.     <authentication-provider user-service-ref="securityManager">  
  22.         <password-encoder hash="md5"/>  
  23.     </authentication-provider>  
  24.        
  25.     <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">  
  26.         <beans:property name="allowIfAllAbstainDecisions" value="false"/>  
  27.         <beans:property name="decisionVoters">  
  28.             <beans:list>  
  29.                 <beans:bean class="org.springframework.security.vote.RoleVoter"/>  
  30.                 <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/>  
  31.             </beans:list>  
  32.         </beans:property>  
  33.     </beans:bean>  
  34.        
  35.     <beans:bean id="resourceSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">  
  36.         <beans:property name="authenticationManager" ref="authenticationManager"/>  
  37.         <beans:property name="accessDecisionManager" ref="accessDecisionManager"/>  
  38.         <beans:property name="objectDefinitionSource" ref="secureResourceFilterInvocationDefinitionSource" />  
  39.         <beans:property name="observeOncePerRequest" value="false" />  
  40.         <custom-filter after="LAST" />  
  41.     </beans:bean>  
  42.        
  43.     <beans:bean id="secureResourceFilterInvocationDefinitionSource" class="com.javaeye.sample.security.interceptor.SecureResourceFilterInvocationDefinitionSource" />  
  44.        
  45. </beans:beans>  
<beans:beans xmlns="http://www.springframework.org/schema/security"      xmlns:beans="http://www.springframework.org/schema/beans"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd                          http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">      <beans:bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener" />      <http access-denied-page="/403.jsp" >    <intercept-url pattern="/static/**" filters="none" />    <intercept-url pattern="/template/**" filters="none" />    <intercept-url pattern="/" filters="none" />    <intercept-url pattern="/login.jsp" filters="none" />       <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?error=true" default-target-url="/index" />       <logout logout-success-url="/login.jsp"/>       <http-basic />   </http>     <authentication-manager alias="authenticationManager"/>      <authentication-provider user-service-ref="securityManager">    <password-encoder hash="md5"/>   </authentication-provider>      <beans:bean id="accessDecisionManager" class="org.springframework.security.vote.AffirmativeBased">       <beans:property name="allowIfAllAbstainDecisions" value="false"/>       <beans:property name="decisionVoters">           <beans:list>               <beans:bean class="org.springframework.security.vote.RoleVoter"/>               <beans:bean class="org.springframework.security.vote.AuthenticatedVoter"/>           </beans:list>       </beans:property>   </beans:bean>      <beans:bean id="resourceSecurityInterceptor" class="org.springframework.security.intercept.web.FilterSecurityInterceptor">    <beans:property name="authenticationManager" ref="authenticationManager"/>       <beans:property name="accessDecisionManager" ref="accessDecisionManager"/>       <beans:property name="objectDefinitionSource" ref="secureResourceFilterInvocationDefinitionSource" />       <beans:property name="observeOncePerRequest" value="false" />       <custom-filter after="LAST" />   </beans:bean>      <beans:bean id="secureResourceFilterInvocationDefinitionSource" class="com.javaeye.sample.security.interceptor.SecureResourceFilterInvocationDefinitionSource" />     </beans:beans>  



请注意,由于我们所实现的,是FilterSecurityInterceptor中的一个开放接口,所以我们实际上定义了一个新的bean,并通过<custom-filter after="LAST" />插入到过滤器链中去。

Spring Security对象的访问

1. 访问当前登录用户

Spring Security提供了一个线程安全的对象:SecurityContextHolder,通过这个对象,我们可以访问当前的登录用户。我写了一个类,可以通过静态方法去读取:

Java代码 复制代码
  1. public class SecurityUserHolder {   
  2.   
  3.     /**  
  4.      * Returns the current user  
  5.      *   
  6.      * @return  
  7.      */  
  8.     public static User getCurrentUser() {   
  9.         return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();   
  10.     }   
  11.   
  12. }  
public class SecurityUserHolder {     /**    * Returns the current user    *     * @return    */   public static User getCurrentUser() {    return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();   }    }



2. 访问当前登录用户所拥有的权限

通过上面的分析,我们知道,用户所拥有的所有权限,其实是通过UserDetails接口中的getAuthorities()方法获得的。只要实现这个接口,就能实现需求。在我的代码中,不仅实现了这个接口,还在上面做了点小文章,这样我们可以获得一个用户所拥有权限的字符串表示:

Java代码 复制代码
  1. /* (non-Javadoc)  
  2.  * @see org.springframework.security.userdetails.UserDetails#getAuthorities()  
  3.  */  
  4. public GrantedAuthority[] getAuthorities() {   
  5.     List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());   
  6.     for(Role role : roles) {   
  7.         grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));   
  8.     }   
  9.        return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);   
  10. }   
  11.   
  12. /**  
  13.  * Returns the authorites string  
  14.  *   
  15.  * eg.   
  16.  *    downpour --- ROLE_ADMIN,ROLE_USER  
  17.  *    robbin --- ROLE_ADMIN  
  18.  *   
  19.  * @return  
  20.  */  
  21. public String getAuthoritiesString() {   
  22.     List<String> authorities = new ArrayList<String>();   
  23.     for(GrantedAuthority authority : this.getAuthorities()) {   
  24.         authorities.add(authority.getAuthority());   
  25.     }   
  26.     return StringUtils.join(authorities, ",");   
  27. }  
 /* (non-Javadoc)    * @see org.springframework.security.userdetails.UserDetails#getAuthorities()    */   public GrantedAuthority[] getAuthorities() {    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(roles.size());       for(Role role : roles) {        grantedAuthorities.add(new GrantedAuthorityImpl(role.getName()));       }          return grantedAuthorities.toArray(new GrantedAuthority[roles.size()]);   }      /**    * Returns the authorites string    *     * eg.     *    downpour --- ROLE_ADMIN,ROLE_USER    *    robbin --- ROLE_ADMIN    *     * @return    */   public String getAuthoritiesString() {       List<String> authorities = new ArrayList<String>();       for(GrantedAuthority authority : this.getAuthorities()) {           authorities.add(authority.getAuthority());       }       return StringUtils.join(authorities, ",");   }



3. 访问当前登录用户能够访问的资源

这就涉及到用户(User),权限(Role)和资源(Resource)三者之间的对应关系。我同样在User对象中实现了一个方法:

Java代码 复制代码
  1. /**  
  2.  * @return the roleResources  
  3.  */  
  4. public Map<String, List<Resource>> getRoleResources() {   
  5.     // init roleResources for the first time   
  6.     if(this.roleResources == null) {               
  7.         this.roleResources = new HashMap<String, List<Resource>>();   
  8.                
  9.         for(Role role : this.roles) {   
  10.             String roleName = role.getName();   
  11.             Set<Resource> resources = role.getResources();   
  12.             for(Resource resource : resources) {   
  13.                 String key = roleName + "_" + resource.getType();   
  14.                     if(!this.roleResources.containsKey(key)) {   
  15.                         this.roleResources.put(key, new ArrayList<Resource>());   
  16.                 }   
  17.                     this.roleResources.get(key).add(resource);                     
  18.             }   
  19.         }   
  20.                
  21.     }   
  22.     return this.roleResources;   
  23. }  
/**   * @return the roleResources   */  public Map<String, List<Resource>> getRoleResources() {   // init roleResources for the first time   if(this.roleResources == null) {       this.roleResources = new HashMap<String, List<Resource>>();         for(Role role : this.roles) {     String roleName = role.getName();     Set<Resource> resources = role.getResources();     for(Resource resource : resources) {      String key = roleName + "_" + resource.getType();       if(!this.roleResources.containsKey(key)) {        this.roleResources.put(key, new ArrayList<Resource>());      }       this.roleResources.get(key).add(resource);          }    }        }   return this.roleResources;  }



这里,会在User对象中设置一个缓存机制,在第一次取的时候,通过遍历User所有的Role,获取相应的Resource信息。

代码示例

在附件中,我给出了一个简单的例子,把我上面所讲到的所有内容整合在一起,是一个eclipse的工程,大家可以下载进行参考。

  • Spring Security 2 配置精讲(2) - wolfgangkiefer - wolfgangkiefer的博客
  • 大小: 26.3 KB
  评论这张
 
阅读(471)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017