`
zhangziyangup
  • 浏览: 1076139 次
文章分类
社区版块
存档分类
最新评论

基于 Struts 2 拦截器实现细粒度的基于角色的存取控制

 
阅读更多

引言

Apache Struts 作为最成功的 MVC Web 框架早已得到了广泛的应用,但是其自身也暴露出不少缺点,从而引出了 Struts 2 。 Struts 2 摒弃了原来 Struts 1 的设计, 而是转向了 webwork2,并结合 Struts 已有的优点,试图打造出一个集众家所长的完美 Web 框架。 Struts 2 因此也具备 webwork2 中的一个非常重要的特性 - 拦截器 (Interceptor) 。拦截器会在 Action 执行之前和之后被执行(如下图),是一种典型 AOP 实现。


图 1. Struts 2 的体系结构

Struts 2 本身提供了一个 org.apache.struts2.interceptor.RolesInterceptor 拦截器以方便开发人员来实现存取控制。但该拦截器的实现是建立在 J2EE 容器提供的存取控制机制之上的。容器提供的存取控制实现粒度较粗,往往无法满足多数应用的需求。在许多项目中,用户所应该具有的权限是由多种因素而决定,往往在不同的上下文中拥有不同的角色。例如在一个社交项目中,一个用户会在不同的社团里拥有不同的角色,如成员,管理员,来宾等。他的具体角色取决于当前所处社团的标识符。另外,用户的角色还和他所要操作的资源类型有关。比如,在这个社交站点中,用户可以创建自己的日程表,把这个日程表共享给其他用户或者委托给其他人管理。这样对日程表这种类型资源,就会有创建者,阅览者和管理者三种角色。在更复杂应用中,用户的角色可能还会受更多因素决定,这就要求存取控制要有更细的粒度,能够处理更加复杂的逻辑。

为了满足这个需求,在基于 Struts 2 的 Web 应用开发中,我们也可以利用拦截器来实现一个应用托管的基于角色的存取控制(RBAC, Role-Based Access Control)系统, 让其能够管理更细粒度的资源。该系统在 Struts 2 的配置文件中定义 Action 可以由那些角色来调用,即对角色进行授权。拦截器在 Action 调用之前,对当前用户进行权限认证来决定 Action 是否应该被执行。

下面我们就基于 Hibernate+Spring+Struts2 框架来完成这个系统的实现。为了使系统结构更加清晰易于维护,我们将这个系统分为域模型层、持久层和服务层来实现。这种分层结构是目前 Web 开发广为使用的一种模式。

模型层实现

这系统中我们只需要一个实体 UserRole, 用来定义用户在不同的上下文中所具有的角色。在清单中,我们使用了 Java Persistence API (Hibernate 从 3.2 开始已经开始支持 JPA)中提供的 JDK 5.0 注解来对模型到数据库表之间的映射进行定义。


清单 1.

  1. @Entity
  2. publicclassUserRole{
  3. privateLongid;
  4. privateUseruser;
  5. privateStringobjectType;
  6. privateLongobjectId;
  7. privateStringrole;
  8. publicUserRole(LonguserId,Stringrole,StringobjectType,LongobjectId){
  9. Useruser=newUser();
  10. user.setId(userId);
  11. this.user=user;
  12. this.role=role;
  13. this.objectType=objectType;
  14. this.objectId=objectId;
  15. }
  16. @Id
  17. @GeneratedValue(strategy=GenerationType.AUTO)
  18. publicLonggetId(){
  19. returnid;
  20. }
  21. publicvoidsetId(Longid){
  22. this.id=id;
  23. }
  24. @ManyToOne
  25. @JoinColumn(name="userId",nullable=false)
  26. publicUsergetUser(){
  27. returnuser;
  28. }
  29. publicvoidsetUser(Useruser){
  30. this.user=user;
  31. }
  32. publicStringgetObjectType(){
  33. returnobjectType;
  34. }
  35. publicvoidsetObjectType(StringobjectType){
  36. this.objectType=objectType;
  37. }
  38. publicLonggetObjectId(){
  39. returnobjectId;
  40. }
  41. publicvoidsetObjectId(LongobjectId){
  42. this.objectId=objectId;
  43. }
  44. publicStringgetRole(){
  45. returnrole;
  46. }
  47. publicvoidsetRole(Stringrole){
  48. this.role=role;
  49. }
  50. }

注意这里边有两个比较特殊的字段 objectTypeobjectId,它们用来表明用户在具体哪个资源上拥有的角色。 objectType 指资源的类型,objectId 指资源的标识。比如我们要将用户 Mike 加为某个日程表的管理员,则表中新增记录的 user 字段为 Mike 在 user 表中的 ID,objectType 为“calendar”,objectID 为这个日程表 ID,role 为角色的名字“admin”。当然,如果您的应用中不同类型资源都使用唯一的全局 ID,objectType 这个字段也可以省略。

DAO 层实现

代码清单 2 定义了对 UserRole 进行 CRUD 的 DAO 接口,代码清单 3 则是它的实现。通过 @PersistenceContext 注解来让容器注入 JPA 中的实体管理器 EntityManager 。 UserRoleDaoImpl 调用 EntityManager 来对 UserRole 进行持久化到数据库中。


清单 2
				
public interface UserRoleDao { 
 public void create(UserRole userRole); 
 public void update(UserRole userRole); 
 public UserRole find(Long userId, String objectType, Long objectId); 
 }


清单 3

  1. publicclassUserRoleDaoImplimplementsUserRoleDao{
  2. privateEntityManagerentityManager;
  3. publicEntityManagergetEntityManager(){
  4. returnentityManager;
  5. }
  6. @PersistenceContext
  7. publicvoidsetEntityManager(EntityManagerentityManager){
  8. this.entityManager=entityManager;
  9. }
  10. publicvoidcreate(UserRoleuserRole){
  11. entityManager.persist(userRole);
  12. }
  13. publicUserRolefind(LonguserId,StringobjectType,LongobjectId){
  14. Queryquery=entityManager.createQuery(
  15. "FROMUserRoleurWHEREur.user.id="+
  16. userId+
  17. "ANDur.objectType='"+
  18. objectType+
  19. "'ANDur.objectId="+
  20. objectId);
  21. Listresult=query.getResultList();
  22. if(result.size()==0)
  23. returnnull;
  24. return(UserRole)result.get(0);
  25. }
  26. publicvoidupdate(UserRoleuserRole){
  27. entityManager.merge(userRole);
  28. }
  29. }

服务层实现

创建一个 RoleService 接口 (清单 4) 作为 façade, 清单 5 是具体实现。 RoleServiceImpl 的实现很简单,主要是封装了为用户分配角色和查询用户角色。注解 Transactional 用来将方法放置在一个事务中进行。在类声明上的 @Transactional(readOnly = true) 表示默认的事务为只读。 setUserRole 方法需要写入数据到数据库中,因此我们将其 readOnly 属性设置成 false.


清单 4
				
public interface RoleService { 
    public void setUserRole(Long userId, String role, String objectType, Long objectId); 
    public String findRole(Long userId, String objectType, Long objectId); 
 }


清单 5

  1. @Transactional(readOnly=true)
  2. publicclassRoleServiceImplimplementsRoleService{
  3. privateUserRoleDaouserRoleDao;
  4. publicvoidsetUserRoleDao(UserRoleDaouserRoleDao){
  5. this.userRoleDao=userRoleDao;
  6. }
  7. @Transactional(readOnly=false)
  8. publicvoidsetUserRole(LonguserId,Stringrole,StringobjectType,LongobjectId){
  9. UserRoleuserRole=newUserRole(userId,role,objectType,objectId);
  10. UserRoleuserRoleInDB=userRoleDao.find(userId,objectType,objectId);
  11. if(null==userRoleInDB){
  12. userRoleDao.create(userRole);
  13. }else{
  14. userRole.setId(userRoleInDB.getId());
  15. userRoleDao.update(userRole);
  16. }
  17. }
  18. publicStringfindRole(LonguserId,StringobjectType,LongobjectId){
  19. UserRoleuserRole=userRoleDao.find(userId,objectType,objectId);
  20. if(userRole==null){
  21. returnnull;
  22. }
  23. returnuserRole.getRole();
  24. }
  25. }

拦截器的实现

拦截器会在 Action 被执行之前被 Struts 2 框架所调用,我们利用这个特性来完成对用户身份的认证,只有用户具有正确角色方能执行 Action 。具体哪些角色可以执行 Action,需要在 Struts 2 的配置文件中指定,将在下一小节中详细阐述。这一点和 Struts 2 内置的 RolesInterceptor 类似,但我们的拦截器可以通过 objectTypeobjectId 来实现更加细粒度的认证。

要创建一个用于用户角色认证的拦截器。需要让其实现 com.opensymphony.xwork2.interceptor.Interceptor 接口并对 String intercept(ActionInvocation actionInvocation) throws Exception 方法进行实现。 如清单 6 。成员变量 roleService 是通过 Spring 的依赖注入被赋予 RoleServiceImpl 。 allowedRolesdisallowedRoles 分别存储了允许和不允许执行 Action 的角色,两者不能同时存在。 objectTypeobjectIdKey 分别表示资源的类型和资源 ID 在 HTTP 请求中的参数名。它们是做为 Interceptor 的参数在 Struts 2 配置文件中进行设置,会自动由 Struts 2 框架填充进来。


清单 6

  1. publicclassRBACInterceptorimplementsInterceptor{
  2. publicstaticfinalStringFORBIDDEN="forbidden";
  3. privateList<String>allowedRoles=newArrayList<String>();
  4. privateList<String>disallowedRoles=newArrayList<String>();
  5. privateRoleServiceroleService;
  6. privateStringobjectType;
  7. privateStringobjectIdKey;
  8. publicvoidsetRoleService(RoleServiceroleService){
  9. this.roleService=roleService;
  10. }
  11. publicvoidsetObjectType(StringobjectType){
  12. this.objectType=objectType;
  13. }
  14. publicvoidsetObjectIdKey(StringobjectIdKey){
  15. this.objectIdKey=objectIdKey;
  16. }
  17. publicvoidsetAllowedRoles(Stringroles){
  18. if(roles!=null)
  19. allowedRoles=Arrays.asList(roles.split("[]*,[]*"));
  20. }
  21. publicvoidsetDisallowedRoles(Stringroles){
  22. if(roles!=null)
  23. disallowedRoles=Arrays.asList(roles.split("[]*,[]*"));
  24. }
  25. publicvoidinit(){
  26. }
  27. publicvoiddestroy(){
  28. }
  29. publicStringintercept(ActionInvocationactionInvocation)throwsException{
  30. HttpServletRequestrequest=ServletActionContext.getRequest();
  31. //Getobjectid
  32. LongobjectId=Long.valueOf(request.getParameter(objectIdKey));
  33. Mapsession=actionInvocation.getInvocationContext().getSession();
  34. //Getcurrentuserid
  35. LonguserId=(Long)session.get(Constant.KEY_CURRENT_USER);
  36. //Gettheuserrole
  37. StringuserRole=roleService.findRole(userId,objectType,objectId);
  38. if(!isAllowed(userRole)){
  39. //forbidinvokingtheaction
  40. returnFORBIDDEN;
  41. }else{
  42. //allowinvokingtheaction
  43. returnactionInvocation.invoke();
  44. }
  45. }
  46. //Checkifthecurrentuserhascorrectroletoinvoketheaction
  47. protectedbooleanisAllowed(StringuserRole){
  48. if(allowedRoles.size()>0){
  49. if(userRole==null)
  50. returnfalse;
  51. returnallowedRoles.contains(userRole);
  52. }elseif(disallowedRoles.size()>0){
  53. if(userRole==null)
  54. returntrue;
  55. return!disallowedRoles.contains(userRole);
  56. }
  57. returntrue;
  58. }
  59. }

intercept 方法中我们根据当前用户的 ID,HTTP 请求参数中获得资源的 ID,所存取的资源类型来调用 RoleService 获得用户的角色。 然后再判断该角色是否在 allowedRolesdisallowedRoles 中来确定用户是否有权限调用 Action 。如果用户没权限,则将请求发送到名为“forbidden”的 result 。从这里可以看出,用户的角色验证与身份验证的作用完全不同。身份验证是验证用户是否网站注册用户,而角色认证是在用户为注册用户的前提下对用户相对于站内各种资源扮演的角色的辨别。

上面代码中用到了判断用户是否具有运行 Action 所要求的角色的函数 isAllowed()。它首先根据用户 ID 和 Action 作用于的对象的类型和 ID 从数据库查询到用户对应的角色,然后将用户角色与允许角色的列表逐个比较。如果允许角色列表包含用户实际角色则返回真,否则返回假;如果允许角色列表为空,则将用户角色与禁止角色的列表比较,如果用户的角色被禁止,则返回假,否则返回真。如果两个列表都为空,也返回真。这样既可以对某个 Action 配置允许访问角色列表,也可以配置拒绝访问列表。

使用

首先我需要在 Spring 的配置文件中添加系统中所涉及到各个 POJO,如清单 7 。


清单 7

  1. <!--DataAccessObjects-->
  2. <beanid="userRoleDao"class="com.sample.security.dao.impl.UserRoleDaoImpl"/>
  3. <!--ServiceObjects-->
  4. <beanid="roleService"
  5. class="com.sample.security.service.impl.RoleServiceImpl">
  6. <propertyname="userRoleDao"ref="userRoleDao"/>
  7. </bean>
  8. <!--InterceptorObjects-->
  9. <beanid="RBACInterceptor"scope="prototype"
  10. class="com.sample.security.interceptor.RBACInterceptor">
  11. <propertyname="roleService"ref="roleService"/>
  12. </bean>

然后需要在 Struts 配置文件中对需要进行存取控制的 Action 进行配置。首先定义我们实现的拦截器,并把其加到拦截器栈中。在 <interceptors> …… </interceptors> 中添加下面的代码。

<interceptor name="RBAC ” class="RBACInterceptor" />

现在我们可以将 RBAC 拦截器添加到任意的 interceptor-stack 中,或者直接配置到任意的 Action 。添加下面清单中的内容到 Struts 2 配置文件中,将能够对在一个日程表中删除会议进行控制。


清单 8

  1. <actionname="deleteMeeting"class="com.demo.action.DeleteMeetingAction">
  2. <result>/WEB-INF/jsp/deleteMeetingResult.jsp</result>
  3. <resultname="forbidden">/WEB-INF/jsp/forbidden.jsp</result>
  4. <interceptor-refname="RBAC">
  5. <paramname="allowedRoles">admin,owner</param>
  6. <paramname="objectType">calendar</param>
  7. <paramname="objectIdKey">id</param>
  8. </interceptor-ref>
  9. <interceptor-refname="defaultStack"/>
  10. </action>

至于用户角色的分配,我们可以定义一个 Action 通过 RoleService 来创建。如下面清单 9 的配置和清单 10 的代码实现了一个 Action 允许日程表的创建者来分配角色给其它人。


清单 9

  1. <actionname="assignCalendarRole"class="com.demo.action.AssignCalendarRoleAction">
  2. <result>/WEB-INF/jsp/deleteMeetingResult.jsp</result>
  3. <resultname="forbidden">/WEB-INF/jsp/forbidden.jsp</result>
  4. <interceptor-refname="RBAC">
  5. <paramname="allowedRoles">owner</param>
  6. <paramname="objectType">calendar</param>
  7. <paramname="objectIdKey">id</param>
  8. </interceptor-ref>
  9. <interceptor-refname="defaultStack"/>
  10. </action>
清单 10

  1. publicclassAssignCalendarRoleActionextendsActionSupport{
  2. privateRoleServiceroleService;
  3. privateLonguserId=0;
  4. privateStringuserRole="reader";
  5. privateLongid=0;
  6. publicAssignCalendarRoleAction(RoleServiceroleService){
  7. this.roleService=roleService;
  8. }
  9. publicStringexecute(){
  10. roleService.setUserRole(userId,userRole,"calendar",id);
  11. returnSUCCESS;
  12. }
  13. }

结束语

本文介绍了如何在 Spring+Hibernate+Struts2 框架中实现一个应用托管的 RBAC 系统,不同于容器提供的 RBAC,它能够更加细粒度地对各种资源进行存取控制。这里的实现非常简单,还需要许多地方可以进行扩展和完善(比如对用户组的支持),希望能对读者起到抛砖引玉的作用。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics