学习Acegi应用到实际项目中(11)- 切换用户

  在某些应用场合中,可能需要用到切换用户的功能,从而以另一用户的身份进行相关操作。这一点类似于在Linux系统中,用su命令切换到另一用户进行相关操作。
  既然实际应用中有这种场合,那么我们就有必要对其进行研究,以求在需要时把它加入到应用中。那么,接下来我们就来研究下如何在Acegi中实现切换用户的功能。

  一般来说,切换用户功能是从高级用户切换到普通用户,从而以普通用户的身份来进行一些操作。相反,普通用户通常是不能切换为高级用户的,如果可以的话那就是越权了。

实现步骤:
1、 添加SwitchUserProcessingFilter过滤器
  增加以下SwitchUserProcessingFilter的配置,并将switchUserProcessingFilter添加到FilterChainProxy过滤器链中。

<bean id="switchUserProcessingFilter" class="org.acegisecurity.ui.switchuser.SwitchUserProcessingFilter">  
  <property name="userDetailsService" ref="jdbcDaoImpl" />  
  <property name="switchUserUrl"><value>/j_acegi_switch_user</value></property>  
  <property name="exitUserUrl"><value>/j_acegi_exit_user</value></property>  
  <property name="targetUrl"><value>/index.jsp</value></property>  
</bean> 

  属性说明:
    userDetailsService:该属性与前面章节org.acegisecurity.providers.dao.DaoAuthenticationProvider 中的userDetailsService属性一样,用于暴露用户的相关信息,如:用户名、密码、权限等。
    switchUserUrl:该属性用于指定切换到另一用户时的入口URL,此处为/j_acegi_switch_user。
    exitUserUrl:该属性用于指定在切换用户后,退回到原来用户身份的入口URL,此处为/j_acegi_exit_user。
    targetUrl:在用户成功切换用户或退回原来用户身份后,过滤器会将用户带到targetUrl所指定的URL中

2、增加切换用户页面switchUser.jsp
  以下为核心代码:

<form action="<c:url value='j_acegi_switch_user'/>" method="POST">  
      <table>  
        <tr><td>User:</td><td><input type='text' name='j_username'></td></tr>  
        <tr><td colspan='2'><input name="switch" type="submit" value="Switch to User"></td></tr>  
      </table>  
</form>

  其中,j_username是我们必须提供的目标用户名。由于SwitchUserProcessingFilter中未暴露j_username这一属性,故我们不能自定义其名字。所以,我们只要提供了请求路径和目标用户名,就可以实现切换到指定用户的功能。

3、增加退回原来用户身份的页面exitUser.jsp
  以下为核心代码:

<form action="<c:url value='j_acegi_exit_user'/>" method="POST">  
    <table>  
        <tr><td colspan='2'><input name="exit" type="submit" value="Exit"></td></tr>  
    </table>  
</form> 

  这部分比较简单,只要提交请求路径j_acegi_exit_user,就可以实现退回原来用户身份的功能。

4、在filterInvocationInterceptor中增加安全授权配置
  为了确保切换用户功能只能从高级用户切换到普通用户,我们必须在Web资源授权中增加相关配置:

<bean id="filterInvocationInterceptor"  
    class="org.acegisecurity.intercept.web.FilterSecurityInterceptor">  
    <property name="authenticationManager" ref="authenticationManager" />  
    <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager" />  
    <property name="objectDefinitionSource">  
        <value><![CDATA[ 
            ...... 
            /switchuser.jsp=AUTH_SUPERUSER 
            /j_acegi_switch_user=AUTH_SUPERUSER 
            ...... 
        ]]></value>  
    </property>  
</bean>  

  这样,我们指定了只有超级用户才能访问切换用户页面和切换用户的URL。

5、例子说明
  在例子中,只是简单的实现了切换功能。系统中有两个用户,分别是root和readonly,其中root拥有增、删、改、查功能,而readonly只有查看功能。当我们从root切换到readonly用户后,我们就只有查看数据,而不能进行增、删、改等操作。只有当我们退回root身份后,才能拥有全部操作功能

猜你喜欢

转载自www.cnblogs.com/cainiaomahua/p/8920678.html