---
title: "Acegi Security -- Spring下最优秀的安全系统"
author: "yefei"
date: "2010-07-30T15:16:23Z"
tags: []
categories: ["企业架构"]
slug: "acegi-security-spring"
draft: false
lastmod: "2010-07-30T16:07:23Z"
id: 725461
url: "https://yefei.iteye.com/blog/725461"
---

一 Acegi安全系统介绍 

 

   Acegi是Spring Framework 下最成熟的安全系统，它提供了强大灵活的企业级安全服务，如完善的认证和授权机制，Http资源访问控制，Method 调用访问控制，Access Control List (ACL) 基于对象实例的访问控制，Yale Central Authentication Service (CAS) 耶鲁单点登陆，X509 认证，当前所有流行容器的认证适配器，Channel Security频道安全管理等功能。

## 1.1 网站资源

官方网站      [http://acegisecurity.sourceforge.net](http://acegisecurity.sourceforge.net/)  
论坛            [http://forum.springframework.org/forumdisplay.php?f=33](http://forum.springframework.org/forumdisplay.php?f=33)  
Jira              [http://opensource.atlassian.com/projects/spring/browse/SEC](http://opensource.atlassian.com/projects/spring/browse/SEC)

## 1.2 多方面的安全控制粒度

1. URL 资源访问控制  
    http://apps:8080/index.htm -&gt; for public  
    http://apps:8080/user.htm -&gt; for authorized user
2. 方法调用访问控制  
   public void getData() -&gt; all user  
   public void modifyData() -&gt; supervisor only
3. 对象实例保护  
   order.getValue() &lt; $100 -&gt; all user  
   order.getValue() &gt; $100 -&gt; supervisor only

## 1.3 非入侵式安全架构

1. 基于Servlet Filter和Spring aop,  使商业逻辑和安全逻辑分开，结构更清晰
2. 使用Spring 来代理对象，能方便地保护方法调用

## 1.4 其它安全架构

    Acegi只是安全框架之一，其实还存在其它优秀的安全框架可供选择：

- JAAS ：[http://java.sun.com/products/jaas/](http://java.sun.com/products/jaas/)
- Seraph: [http://opensource.atlassian.com/seraph/](http://opensource.atlassian.com/seraph/)
- jSai - Servlet Security : [http://oss.ipov.org/jsai/](http://oss.ipov.org/jsai/)
- Gabriel : [http://gabriel.codehaus.org/](http://gabriel.codehaus.org/)
- JOSSO : [http://www.josso.org/](http://www.josso.org/)
- Kasai: [http://www.manentiasoftware.com/kasai/goToHome.action](http://www.manentiasoftware.com/kasai/goToHome.action)
- jPAM : [http://jpam.sourceforge.net/](http://jpam.sourceforge.net/)
- OpenSAML : [http://www.opensaml.org/](http://www.opensaml.org/)

二 Acegi安全系统的配置

 

     Acegi 的配置看起来非常复杂,但事实上在实际项目的安全应用中我们并不需要那么多功能,清楚的了解Acegi配置中各项的功能，有助于我们灵活的运用Acegi于实践中。

## 2.1 在Web.xml中的配置

1)  **FilterToBeanProxy**  
　　Acegi通过实现了Filter接口的FilterToBeanProxy提供一种特殊的使用Servlet Filter的方式，它委托Spring中的Bean -- FilterChainProxy来完成过滤功能，这好处是简化了web.xml的配置，并且充分利用了Spring IOC的优势。FilterChainProxy包含了处理认证过程的filter列表，每个filter都有各自的功能。

```
    <filter>
        <filter-name>Acegi Filter Chain Proxy</filter-name>
        <filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
        <init-param>
            <param-name>targetClass</param-name>
            <param-value>org.acegisecurity.util.FilterChainProxy</param-value>
        </init-param>
    </filter>
```

2\) **filter-mapping**  
　　&lt;filter-mapping&gt;限定了FilterToBeanProxy的URL匹配模式,只有\*.do和\*.jsp和/j\_acegi\_security\_check 的请求才会受到权限控制，对javascript,css等不限制。

```
   <filter-mapping>
      <filter-name>Acegi Filter Chain Proxy</filter-name>
      <url-pattern>*.do</url-pattern>
    </filter-mapping>
    
    <filter-mapping>
      <filter-name>Acegi Filter Chain Proxy</filter-name>
      <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    
    <filter-mapping>
      <filter-name>Acegi Filter Chain Proxy</filter-name>
      <url-pattern>/j_acegi_security_check</url-pattern>
    </filter-mapping>
```

3\) **HttpSessionEventPublisher**  
　　&lt;listener&gt;的HttpSessionEventPublisher用于发布HttpSessionApplicationEvents和HttpSessionDestroyedEvent事件给spring的applicationcontext。

```
    <listener>
        <listener-class>org.acegisecurity.ui.session.HttpSessionEventPublisher</listener-class>
    </listener>
```

## 2.2 在applicationContext-acegi-security.xml中

### 2.2.1 FILTER CHAIN

　　FilterChainProxy会按顺序来调用这些filter,使这些filter能享用Spring ioc的功能, CONVERT\_URL\_TO\_LOWERCASE\_BEFORE\_COMPARISON定义了url比较前先转为小写， PATTERN\_TYPE\_APACHE\_ANT定义了使用Apache ant的匹配模式

```
    <bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy">
        <property name="filterInvocationDefinitionSource">
            <value>
                CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
                PATTERN_TYPE_APACHE_ANT
               /**=httpSessionContextIntegrationFilter,authenticationProcessingFilter,
basicProcessingFilter,rememberMeProcessingFilter,anonymousProcessingFilter,
 exceptionTranslationFilter,filterInvocationInterceptor
            </value>
        </property>
    </bean>
```

### 2.2.2 基础认证

1\) **authenticationManager**  
　　起到认证管理的作用，它将验证的功能委托给多个Provider，并通过遍历Providers, 以保证获取不同来源的身份认证，若某个Provider能成功确认当前用户的身份，authenticate()方法会返回一个完整的包含用户授权信息的Authentication对象，否则会抛出一个AuthenticationException。  
Acegi提供了不同的AuthenticationProvider的实现,如：  
        DaoAuthenticationProvider 从数据库中读取用户信息验证身份  
        AnonymousAuthenticationProvider 匿名用户身份认证  
        RememberMeAuthenticationProvider 已存cookie中的用户信息身份认证  
        AuthByAdapterProvider 使用容器的适配器验证身份  
        CasAuthenticationProvider 根据Yale中心认证服务验证身份, 用于实现单点登陆  
        JaasAuthenticationProvider 从JASS登陆配置中获取用户信息验证身份  
        RemoteAuthenticationProvider 根据远程服务验证用户身份  
        RunAsImplAuthenticationProvider 对身份已被管理器替换的用户进行验证  
        X509AuthenticationProvider 从X509认证中获取用户信息验证身份  
        TestingAuthenticationProvider 单元测试时使用

        每个认证者会对自己指定的证明信息进行认证，如DaoAuthenticationProvider仅对UsernamePasswordAuthenticationToken这个证明信息进行认证。

```
<bean id="authenticationManager" class="org.acegisecurity.providers.ProviderManager">
        <property name="providers">
            <list>
                <ref local="daoAuthenticationProvider"/>
                <ref local="anonymousAuthenticationProvider"/>
                <ref local="rememberMeAuthenticationProvider"/>
            </list>
        </property>
</bean>
```

2\) **daoAuthenticationProvider**  
　　进行简单的基于数据库的身份验证。DaoAuthenticationProvider获取数据库中的账号密码并进行匹配，若成功则在通过用户身份的同时返回一个包含授权信息的Authentication对象，否则身份验证失败，抛出一个AuthenticatiionException。

```
    <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="jdbcDaoImpl"/>
        <property name="userCache" ref="userCache"/>
        <property name="passwordEncoder" ref="passwordEncoder"/>
   </bean>
```

3\) **passwordEncoder**  
　　使用加密器对用户输入的明文进行加密。Acegi提供了三种加密器:  
PlaintextPasswordEncoder—默认，不加密，返回明文.  
ShaPasswordEncoder—哈希算法(SHA)加密  
Md5PasswordEncoder—消息摘要(MD5)加密

```
<bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.Md5PasswordEncoder"/>
```

4\) **jdbcDaoImpl**  
　　用于在数据中获取用户信息。 acegi提供了用户及授权的表结构，但是您也可以自己来实现。通过usersByUsernameQuery这个SQL得到你的(用户ID,密码,状态信息);通过authoritiesByUsernameQuery这个SQL得到你的(用户ID,授权信息)

```
 
<bean id="jdbcDaoImpl" 
class="org.acegisecurity.userdetails.jdbc.JdbcDaoImpl">
        
<property name="dataSource" 
ref="dataSource"/>
        <property 
name="usersByUsernameQuery">
            
<value>select loginid,passwd,1 from users where loginid = 
?</value>
        
</property>
        <property 
name="authoritiesByUsernameQuery">
            
<value>select u.loginid,p.name from users u,roles r,permissions 
p,user_role ur,role_permis rp where u.id=ur.user_id and r.id=ur.role_id and 
p.id=rp.permis_id 
and
                
r.id=rp.role_id and p.status='1' and 
u.loginid=?</value>
        
</property>
</bean>
```

5\) **userCache　&  resourceCache**  
　　缓存用户和资源相对应的权限信息。每当请求一个受保护资源时，daoAuthenticationProvider就会被调用以获取用户授权信息。如果每次都从数据库获取的话，那代价很高，对于不常改变的用户和资源信息来说，最好是把相关授权信息缓存起来。(详见 [2.6.3 资源权限定义扩展](/admin/blogs/725461/Acegi4.htm) )  
userCache提供了两种实现: NullUserCache和EhCacheBasedUserCache, NullUserCache实际上就是不进行任何缓存，EhCacheBasedUserCache是使用Ehcache来实现缓功能。

```
    <bean id="userCacheBackend" 
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
        
<property name="cacheManager" 
ref="cacheManager"/>
        
<property name="cacheName" value="userCache"/>
    </bean>
    <bean id="userCache" 
class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache" 
autowire="byName">
        <property 
name="cache" ref="userCacheBackend"/>
      
</bean>
    <bean id="resourceCacheBackend" 
class="org.springframework.cache.ehcache.EhCacheFactoryBean">
        
<property name="cacheManager" 
ref="cacheManager"/>
        
<property name="cacheName" value="resourceCache"/>
    </bean>
    <bean id="resourceCache" 
class="org.springside.modules.security.service.acegi.cache.ResourceCache" 
autowire="byName">
        <property 
name="cache" ref="resourceCacheBackend"/>
    </bean>
```

6\) **basicProcessingFilter**  
　　用于处理HTTP头的认证信息，如从Spring远程协议(如Hessian和Burlap)或普通的浏览器如IE,Navigator的HTTP头中获取用户信息，将他们转交给通过authenticationManager属性装配的认证管理器。如果认证成功，会将一个Authentication对象放到会话中，否则，如果认证失败，会将控制转交给认证入口点(通过authenticationEntryPoint属性装配)

```
    <bean id="basicProcessingFilter" class="org.acegisecurity.ui.basicauth.BasicProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationEntryPoint" ref="basicProcessingFilterEntryPoint"/>
    </bean>
```

7\) **basicProcessingFilterEntryPoint**  
　　通过向浏览器发送一个HTTP401(未授权)消息，提示用户登录。  
处理基于HTTP的授权过程， 在当验证过程出现异常后的"去向"，通常实现转向、在response里加入error信息等功能。

```
 <bean 
id="basicProcessingFilterEntryPoint" 
class="org.acegisecurity.ui.basicauth.BasicProcessingFilterEntryPoint">
        
<property name="realmName" value="SpringSide Realm"/>
</bean>
```

8\) **authenticationProcessingFilterEntryPoint**  
　　当抛出AccessDeniedException时，将用户重定向到登录界面。属性loginFormUrl配置了一个登录表单的URL,当需要用户登录时，authenticationProcessingFilterEntryPoint会将用户重定向到该URL

```
 
<bean id="authenticationProcessingFilterEntryPoint" 
class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
        
<property 
name="loginFormUrl">
            
<value>/security/login.jsp</value>
        
</property>
        <property 
name="forceHttps" value="false"/>
</bean>
```

## 2.2.3 HTTP安全请求

1\) **httpSessionContextIntegrationFilter**  
　　每次request前 HttpSessionContextIntegrationFilter从Session中获取Authentication对象，在request完后, 又把Authentication对象保存到Session中供下次request使用,此filter必须其他Acegi filter前使用，使之能跨越多个请求。

```
<bean id="httpSessionContextIntegrationFilter" class="org.acegisecurity.context.HttpSessionContextIntegrationFilter"></bean>
    <bean id="httpRequestAccessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
            </list>
        </property>
</bean>
```

2\) **httpRequestAccessDecisionManager**  
　　经过投票机制来决定是否可以访问某一资源(URL或方法)。allowIfAllAbstainDecisions为false时如果有一个或以上的decisionVoters投票通过,则授权通过。可选的决策机制有ConsensusBased和UnanimousBased

```
    <bean id="httpRequestAccessDecisionManager" class="org.acegisecurity.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
            </list>
        </property>
    </bean>
```

3\) **roleVoter**  
 　　必须是以rolePrefix设定的value开头的权限才能进行投票,如AUTH_ , ROLE_

```
    <bean id="roleVoter" class="org.acegisecurity.vote.RoleVoter">
        <property name="rolePrefix" value="AUTH_"/>
   </bean>
```

4）**exceptionTranslationFilter**  
　　异常转换过滤器，主要是处理AccessDeniedException和AuthenticationException，将给每个异常找到合适的"去向" 

```
   <bean id="exceptionTranslationFilter" class="org.acegisecurity.ui.ExceptionTranslationFilter">
        <property name="authenticationEntryPoint" ref="authenticationProcessingFilterEntryPoint"/>
    </bean>
```

5\) **authenticationProcessingFilter**  
　　和servlet spec差不多,处理登陆请求.当身份验证成功时，AuthenticationProcessingFilter会在会话中放置一个Authentication对象，并且重定向到登录成功页面  
         authenticationFailureUrl定义登陆失败时转向的页面  
         defaultTargetUrl定义登陆成功时转向的页面  
         filterProcessesUrl定义登陆请求的页面  
         rememberMeServices用于在验证成功后添加cookie信息

```
    <bean id="authenticationProcessingFilter" class="org.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationFailureUrl">
            <value>/security/login.jsp?login_error=1</value>
        </property>
        <property name="defaultTargetUrl">
            <value>/admin/index.jsp</value>
        </property>
        <property name="filterProcessesUrl">
            <value>/j_acegi_security_check</value>
        </property>
        <property name="rememberMeServices" ref="rememberMeServices"/>
    </bean>
```

6\) **filterInvocationInterceptor**  
　　在执行转向url前检查objectDefinitionSource中设定的用户权限信息。首先，objectDefinitionSource中定义了访问URL需要的属性信息(这里的属性信息仅仅是标志，告诉accessDecisionManager要用哪些voter来投票)。然后，authenticationManager掉用自己的provider来对用户的认证信息进行校验。最后，有投票者根据用户持有认证和访问url需要的属性，调用自己的voter来投票，决定是否允许访问。

```
    <bean id="filterInvocationInterceptor" class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="objectDefinitionSource" ref="filterDefinitionSource"/>
    </bean>
```

7\) **filterDefinitionSource** (详见 [2.6.3 资源权限定义扩展](/admin/blogs/725461/Acegi4.htm))  
　　自定义DBFilterInvocationDefinitionSource从数据库和cache中读取保护资源及其需要的访问权限信息 

```
<bean id="filterDefinitionSource" class="org.springside.modules.security.service.acegi.DBFilterInvocationDefinitionSource">
        <property name="convertUrlToLowercaseBeforeComparison" value="true"/>
        <property name="useAntPath" value="true"/>
        <property name="acegiCacheManager" ref="acegiCacheManager"/>
</bean>
```

## 2.2.4 方法调用安全控制

(详见 [2.6.3 资源权限定义扩展](/admin/blogs/725461/Acegi4.htm))

1\) methodSecurityInterceptor  
　　在执行方法前进行拦截，检查用户权限信息  
2\) methodDefinitionSource  
　　自定义MethodDefinitionSource从cache中读取权限

```
   <bean id="methodSecurityInterceptor" class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="objectDefinitionSource" ref="methodDefinitionSource"/>
    </bean>
    <bean id="methodDefinitionSource" class="org.springside.modules.security.service.acegi.DBMethodDefinitionSource">
        <property name="acegiCacheManager" ref="acegiCacheManager"/>
    </bean>
```

## 2.3 Jcaptcha验证码

采用 [http://jcaptcha.sourceforge.net](http://jcaptcha.sourceforge.net/) 作为通用的验证码方案，请参考SpringSide中的例子，或网上的：  
[http://www.coachthrasher.com/page/blog?entry=jcaptcha\_with\_appfuse](http://www.coachthrasher.com/page/blog?entry=jcaptcha_with_appfuse)。

差沙在此过程中又发现acegi logout filter的错误，进行了修正。

另外它默认提供的图片比较难认，我们custom了一个美观一点的版本。

 

 

 

 

参考：[http://www.springside.org.cn/docs/reference/Acegi.htm](http://www.springside.org.cn/docs/reference/Acegi.htm)

         [http://wiki.springside.org.cn/display/SpringSide3/Overview](http://wiki.springside.org.cn/display/SpringSide3/Overview)