Acegi

acegi保护业务方法 
一、在Acegi配置文件中配置实现保护业务方法
保护业务方法配置(假设不保护领域对象):

<bean id="contactManagerSecurity"
    class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="accessDecisionManager"
        ref="httpRequestAccessDecisionManager" />
    <property name="objectDefinitionSource">
        <value>
            sample.service.IContactManager.create=ROLE_USER
            sample.service.IContactManager.delete=ROLE_ADMIN
            sample.service.IContactManager.getAll=ROLE_USER,ROLE_ADMIN
            sample.service.IContactManager.getById=ROLE_ADMIN
            sample.service.IContactManager.update=ROLE_ADMIN
        </value>
    </property>
</bean>



业务接口和实现类

public interface IContactManager{
  public List getAll();
  public Contact getById(Integer id);
  public void create(Contact contact);
  public void update(Contact contact);
  public void delete(Contact contact);
}
 
public class ContactManager implements IContactManager {
    ……
}



加入保护业务方法的拦截器

<bean id="transactionInterceptor"
    class="org.springframework.transaction.interceptor.TransactionInterceptor">
    <property name="transactionManager">
        <ref bean="transactionManager" />
    </property>
    <property name="transactionAttributeSource">
        <value>
            sample.service.impl.ContactManager.*=PROPAGATION_REQUIRED
        </value>
    </property>
</bean>
 
<!--dao start -->
<bean id="contactDao" class="sample.dao.impl.ContactDao">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
</bean>
 
<!--service start -->
<bean id="contactManagerTarget"
    class="sample.service.impl.ContactManager">
    <property name="contactDao">
        <ref bean="contactDao" />
    </property>
</bean>
 
<bean id="contactManager"
    class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <value>sample.service.IContactManager</value>
    </property>
    <property name="interceptorNames">
        <list>
            <idref local="transactionInterceptor" />
            <STRONG><!-- 加入保护业务方法的拦截器 -->
            <idref bean="contactManagerSecurity"/></STRONG>
            <idref local="contactManagerTarget" />
        </list>
    </property>
</bean>



Run-As认证服务:

有这样一些场合,系统用户必须以其他角色身份去操作某些资源。例如,用户A要访问资源B,而用户A拥有的角色为AUTH_USER,资源B访问的角色必须为AUTH_RUN_AS_DATE,那么此时就必须使用户A拥有角色AUTH_RUN_AS_DATE才能访问资源B。

为了实现这一需求,Acegi为我们提供了Run-As认证服务。下面我们举例说明如何应用Run-As认证服务。

1、用于配置Run-As认证服务的接口与实现类

public interface IRunAsDate {
    public void showDate();
}
 
public class RunAsDate implements IRunAsDate {
    private static final Log log = LogFactory.getLog(RunAsDate.class);
 
    /* (non-Javadoc)
     * @see sample.service.IRunAsDate#showDate()
     */
    public void showDate() {
        log.info("当前日期: " + new Date());
    }
}



对showDate方法进行授权
      设置访问showDate方法必须拥有AUTH_RUN_AS_DATE角色,同时暴露IRunAsDate接口

<bean id="runAsDateImpl"
    class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="proxyInterfaces">
        <value>sample.service.IRunAsDate</value>
    </property>
    <property name="interceptorNames">
        <list>
            <idref local="runAsDateSecurity" />
            <idref local="runAsDateTarget" />
        </list>
    </property>
</bean>
 
<bean id="runAsDateTarget" class="sample.service.impl.RunAsDate"></bean>
 
<bean id="runAsDateSecurity"
    class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
    <property name="alwaysReauthenticate" value="true" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="accessDecisionManager"
        ref="httpRequestAccessDecisionManager" />
    <property name="objectDefinitionSource">
        <value>
            sample.service.IRunAsDate.showDate=AUTH_RUN_AS_DATE
        </value>
    </property>
</bean>



其中,alwaysReauthenticate为true表示每次操作都需要进行身份的验证。在默认情况下,RunAsManagerImpl构建的RunAsUserToken认证对象都是已认证状态。因此,只有设置alwaysReauthenticate为true时,才会触发RunAsImplAuthenticationProvider的认证操作。

配置RunAsImplAuthenticationProvider
      RunAsManagerImpl实例会基于现有的的已认证对象创建新的RunAsUserToken认证类型,而RunAsImplAuthenticationProvider要负责这一认证类型的认证工作。与其他认证提供者一样,必须将其加入authenticationManager中

<bean id="runAsImplAuthenticationProvider"
    class="org.acegisecurity.runas.RunAsImplAuthenticationProvider">
    <property name="key" value="javaee" />
</bean>
 
<bean id="authenticationManager"
    class="org.acegisecurity.providers.ProviderManager">
    <property name="providers">
        <list>
            ……
            <!-- 配置与daoAuthenticationProvider类似 -->
            <ref bean="runAsImplAuthenticationProvider" />
        </list>
    </property>
</bean>



配置RunAsManagerImpl
      RunAsManagerImpl中的key必须与RunAsImplAuthenticationProvider中的key一致,从而保证RunAsManagerImpl 与RunAsImplAuthenticationProvider协同工作。在前面章节中,对于匿名认证与Remember-Me认证中也需要提供类似的key属性值。
      RunAsManagerImpl的rolePrefix属性默认值为ROLE_。由于我们配置的资源需要的角色为AUTH_RUN_AS_DATE,故在此我们将前缀设置为AUTH_。



<bean id="runAsManagerImpl"
    class="org.acegisecurity.runas.RunAsManagerImpl">
    <property name="key" value="javaee" />
    <property name="rolePrefix" value="AUTH_" />
</bean>
 
<bean id="contactManagerSecurity"
    class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="accessDecisionManager"
        ref="httpRequestAccessDecisionManager" />
    <property name="runAsManager" ref="runAsManagerImpl" />
    <property name="objectDefinitionSource">
        <value>
            ……
            sample.service.IContactManager.getAll=ROLE_USER,ROLE_ADMIN
            ,RUN_AS_DATE
            ……
        </value>
    </property>
</bean>



我们对getAll方法配置了RUN_AS_DATE角色,默认时RunAsManagerImpl会从授权信息中获得前缀为”RUN_AS”的角色,同时构建新的授权信息,将rolePrefix添加到角色中,即组成类似AUTH_RUN_AS_DATE的角色。
注意,Run-As认证服务只是临时性替换了现有用户的身份,这一点要比较重视!

在上一节中介绍了通过RDBMS存储web资源授权信息,下面将RDBMS存储业务方法的授权信息

1、修改RdbmsEntryHolder类
前篇保护Web资源时RdbmsEntryHolder类如下:

public class RdbmsEntryHolder implements Serializable {
    // 保护的URL模式

    private String url;
    // 要求的角色集合

    private ConfigAttributeDefinition cad;
    ......
}



由于我们现在所要保护的是业务方法,故我们将url变量易名为method,这样会更加明确。method变量存放类似于“sample.service.IContactManager.create”、“sample.service.IContactManager.update*”的方法名全称。

修改RdbmsSecuredUrlDefinition类
      将RdbmsSecuredUrlDefinition改名为RdbmsSecuredMethodDefinition

public class RdbmsSecuredMethodDefinition extends MappingSqlQuery{
 
    protected static final Log log = LogFactory.getLog(RdbmsSecuredMethodDefinition.class);
      
    public RdbmsSecuredMethodDefinition(DataSource ds) {
        super(ds, SELECT method, roles FROM webresdb ORDER BY id>);
        compile();
    }
 
    /**
     * convert each row of the ResultSet into an object of the result type.
     */
    protected Object mapRow(ResultSet rs, int rownum)
        throws SQLException {
        RdbmsEntryHolder rsh = new RdbmsEntryHolder();
        <STRONG>// 设置业务方法

        rsh.setMethod(rs.getString("method").trim());
          
        ConfigAttributeDefinition cad = new ConfigAttributeDefinition();
          
        String rolesStr = rs.getString("roles").trim();
        // commaDelimitedListToStringArray:Convert a CSV list into an array of Strings

        // 以逗号为分割符, 分割字符串

        String[] tokens =
                StringUtils.commaDelimitedListToStringArray(rolesStr); // 角色名数组

        // 构造角色集合

        for(int i = 0; i < tokens.length;++i)
            cad.addConfigAttribute(new SecurityConfig(tokens[i]));
          
        //设置角色集合

        rsh.setCad(cad);
          
        return rsh;
    }
 
}



自定义实现MethodDefinitionSource接口
      修改RdbmsFilterInvocationDefinitionSource类,改名为RdbmsMethodDefinitionSource,并修改相应方法

protected void initDao() throws Exception {
    this.rdbmsSecuredMethodDefinition =
        new RdbmsSecuredMethodDefinition(this.getDataSource()); // 传入数据源, 此数据源由Spring配置文件注入

    ……
}
 
public ConfigAttributeDefinition getAttributes(Object object) throws IllegalArgumentException {
    if ((object == null) || !this.supports(object.getClass())) {
        throw new IllegalArgumentException("抱歉,目标对象不是MethodInvocation类型");
    }
      
    Method method = ((MethodInvocation) object).getMethod();
      
    List list = this.getRdbmsEntryHolderList();
    if (list == null || list.size() == 0)
        return null;
      
    // 获取方法全称, 如java.util.Set.isEmpty

    String methodString = method.getDeclaringClass().getName() + "." + method.getName();
      
    String mappedName;
    Iterator it = list.iterator();
    <STRONG>// 循环判断当前访问的方法是否设置了角色访问机制, 有则返回ConfigAttributeDefinition(角色集合), 否则返回null</STRONG>

    while (it.hasNext()) {
        RdbmsEntryHolder entryHolder = (RdbmsEntryHolder) it.next();
        mappedName = entryHolder.getMethod();
        boolean matched = pathMatcher.match(entryHolder.getMethod(), methodString);
        //boolean matched = methodString.equals(mappedName) || isMatch(methodString, mappedName);

        if (logger.isDebugEnabled()) {
            logger.debug("匹配到如下Method: '" + methodString + ";模式为 "
                    + entryHolder.getMethod() + ";是否被匹配:" + matched);
        }
 
        // 如果在用户所有被授权的URL中能找到匹配的, 则返回该ConfigAttributeDefinition(角色集合)

        if (matched) {
            return entryHolder.getCad();
        }
    }
      
    return null;
}



通过Spring DI注入RdbmsMethodDefinitionSource

<bean id="contactManagerSecurity"
    class="org.acegisecurity.intercept.method.aopalliance.MethodSecurityInterceptor">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager" />
    <property name="objectDefinitionSource" ref="<STRONG>rdbmsMethodDefinitionSource</STRONG>" />
</bean>
 
<bean id="<STRONG>rdbmsMethodDefinitionSource</STRONG>" class="sample.service.impl.<STRONG>RdbmsMethodDefinitionSource</STRONG>">
    <property name="dataSource" ref="dataSource" />
    <property name="webresdbCache" ref="webresCacheBackend" />
</bean>
 
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
 
<bean id="webresCacheBackend"
    class="org.springframework.cache.ehcache.EhCacheFactoryBean">
    <property name="cacheManager">
        <ref local="cacheManager"/>
    </property>
    <property name="cacheName">
        <value>webresdbCache</value>
    </property>
</bean>






你可能感兴趣的:(DAO,spring,Web,应用服务器,Acegi)