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

本文介绍如何在Spring+Hibernate+Struts2框架中实现细粒度的角色基础存取控制系统(RBAC),以满足不同应用场景下的权限管理需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言

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.  public class UserRole { 
  3.   private Long id; 
  4.   private User user; 
  5.   private String objectType; 
  6.   private Long objectId; 
  7.   private String role; 
  8.   public UserRole(Long userId, String role, String objectType, Long objectId) { 
  9.     User user = new User(); 
  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.   public Long getId() { 
  19.     return id; 
  20.   } 
  21.   public void setId(Long id) { 
  22.     this.id = id; 
  23.   } 
  24.   @ManyToOne 
  25.   @JoinColumn(name = "userId", nullable = false
  26.   public User getUser() { 
  27.     return user; 
  28.   } 
  29.   public void setUser(User user) { 
  30.     this.user = user; 
  31.   } 
  32.   public String getObjectType() { 
  33.     return objectType; 
  34.   } 
  35.   public void setObjectType(String objectType) { 
  36.     this.objectType = objectType; 
  37.   } 
  38.   public Long getObjectId() { 
  39.     return objectId; 
  40.   } 
  41.   public void setObjectId(Long objectId) { 
  42.     this.objectId = objectId; 
  43.   } 
  44.   public String getRole() { 
  45.     return role; 
  46.   } 
  47.   public void setRole(String role) { 
  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

 

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

 

  1. public class UserRoleDaoImpl implements UserRoleDao { 
  2.   private EntityManager entityManager; 
  3.   public EntityManager getEntityManager() { 
  4.     return entityManager; 
  5.   } 
  6.   @PersistenceContext 
  7.   public void setEntityManager(EntityManager entityManager) { 
  8.     this.entityManager = entityManager; 
  9.   } 
  10.   public void create(UserRole userRole) { 
  11.     entityManager.persist(userRole); 
  12.   } 
  13.   public UserRole find(Long userId, String objectType, Long objectId) { 
  14.     Query query = entityManager.createQuery(
  15.       "FROM UserRole ur WHERE ur.user.id=" + 
  16.       userId + 
  17.       " AND ur.objectType='" + 
  18.       objectType + 
  19.       "' AND ur.objectId=" + 
  20.       objectId); 
  21.     List result = query.getResultList(); 
  22.     if (result.size() == 0) 
  23.       return null
  24.     return (UserRole)result.get(0); 
  25.   } 
  26.   public void update(UserRole userRole) { 
  27.     entityManager.merge(userRole); 
  28.   } 
  29.  }

服务层实现

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


清单 4

 

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

 

  1. @Transactional(readOnly = true
  2.  public class RoleServiceImpl implements RoleService { 
  3.  private UserRoleDao userRoleDao; 
  4.  public void setUserRoleDao(UserRoleDao userRoleDao) { 
  5.     this.userRoleDao = userRoleDao; 
  6.  } 
  7.   @Transactional(readOnly = false
  8.   public void setUserRole(Long userId, String role, String objectType, Long objectId) { 
  9.     UserRole userRole = new UserRole(userId, role, objectType, objectId); 
  10.     UserRole userRoleInDB = 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.   public String findRole(Long userId, String objectType, Long objectId) { 
  19.     UserRole userRole = userRoleDao.find(userId, objectType, objectId); 
  20.     if (userRole == null) { 
  21.       return null
  22.     } 
  23.     return userRole.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. public class RBACInterceptor implements Interceptor { 
  2.    public static final String FORBIDDEN = "forbidden"
  3.    private List<String> allowedRoles = new ArrayList<String>(); 
  4.    private List<String> disallowedRoles = new ArrayList<String>(); 
  5.    private RoleService roleService; 
  6.    private String objectType; 
  7.    private String objectIdKey;   
  8.     
  9.    public void setRoleService(RoleService roleService) { 
  10.   this.roleService = roleService; 
  11.    } 
  12.    public void setObjectType(String objectType) { 
  13.     this.objectType = objectType; 
  14.   } 
  15.   public void setObjectIdKey(String objectIdKey) { 
  16.     this.objectIdKey = objectIdKey; 
  17.   } 
  18.   public void setAllowedRoles(String roles) { 
  19.     if (roles != null
  20.       allowedRoles = Arrays.asList(roles.split("[ ]*,[ ]*")); 
  21.   } 
  22.   public void setDisallowedRoles(String roles) { 
  23.     if (roles != null
  24.       disallowedRoles = Arrays.asList(roles.split("[ ]*,[ ]*")); 
  25.   } 
  26.   public void init() { 
  27.   } 
  28.     
  29.   public void destroy() { 
  30.   } 
  31.     
  32.   public String intercept(ActionInvocation actionInvocation) throws Exception { 
  33.     HttpServletRequest request = ServletActionContext.getRequest(); 
  34.     // Get object id 
  35.     Long objectId = Long.valueOf(request.getParameter(objectIdKey)); 
  36.     Map session = actionInvocation.getInvocationContext().getSession(); 
  37.     // Get current user id 
  38.     Long userId = (Long) session.get(Constant.KEY_CURRENT_USER); 
  39.     // Get the user role 
  40.     String userRole = roleService.findRole(userId, objectType, objectId); 
  41.     if (!isAllowed(userRole)) { 
  42.       // forbid invoking the action 
  43.       return FORBIDDEN; 
  44.     } else { 
  45.       // allow invoking the action 
  46.       return actionInvocation.invoke(); 
  47.     } 
  48.   } 
  49.   // Check if the current user has correct role to invoke the action 
  50.   protected boolean isAllowed(String userRole) { 
  51.     if (allowedRoles.size() > 0) { 
  52.       if (userRole == null
  53.         return false
  54.       return allowedRoles.contains(userRole); 
  55.     } else if (disallowedRoles.size() > 0) { 
  56.       if (userRole == null
  57.         return true
  58.       return !disallowedRoles.contains(userRole); 
  59.     } 
  60.     return true
  61.   } 
  62.  }

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

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

使用

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


清单 7

 

  1. <!-- Data Access Objects --> 
  2.   <bean id="userRoleDao" class="com.sample.security.dao.impl.UserRoleDaoImpl"/> 
  3.    
  4.   <!-- Service Objects --> 
  5.   <bean id="roleService" 
  6.     class="com. sample.security.service.impl.RoleServiceImpl" > 
  7.     <property name="userRoleDao" ref="userRoleDao" /> 
  8.   </bean> 
  9.   
  10.   <!-- Interceptor Objects --> 
  11.   <bean id="RBACInterceptor" scope="prototype" 
  12.     class="com. sample.security.interceptor. RBACInterceptor "
  13.     <property name="roleService"  ref="roleService" /> 
  14.   </bean>

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

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

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


清单 8

 

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

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


清单 9

 

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

 

  1. public class AssignCalendarRoleAction extends ActionSupport { 
  2.   private RoleService roleService; 
  3.   private Long userId = 0; 
  4.   private String userRole = "reader"
  5.  private Long id = 0; 
  6.   public AssignCalendarRoleAction (RoleService roleService) { 
  7.     this.roleService = roleService; 
  8.   } 
  9.  public String execute() { 
  10.  roleService.setUserRole(userId, userRole, "calendar", id); 
  11.  return SUCCESS; 
  12.   } 
  13.  }

结束语

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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值