首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

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

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

服务层实现创建一个 RoleService 接口 (清单 4) 作为 façade, 清单 5 是具体实现。 RoleServiceImpl 的实现很简单,主要是封装了为用户分配角色和查询用户角色。注解 Transactional 用来将方法放置在一个事务中进行。在类声明上的 @Transactional(readOnly = true) 表示默认的事务为只读。 setUserRole 方法需要写入数据到数据库中,因此我们将其 readOnly 属性设置成 false.
清单 4
1
2
3
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Transactional(readOnly = true)
public class RoleServiceImpl implements RoleService {

private UserRoleDao userRoleDao;

public void setUserRoleDao(UserRoleDao userRoleDao) {
    this.userRoleDao = userRoleDao;
}

  @Transactional(readOnly = false)
  public void setUserRole(Long userId, String role, String objectType, Long objectId) {
    UserRole userRole = new UserRole(userId, role, objectType, objectId);
    UserRole userRoleInDB = userRoleDao.find(userId, objectType, objectId);
    if (null == userRoleInDB) {
      userRoleDao.create(userRole);
    } else {
      userRole.setId(userRoleInDB.getId());
      userRoleDao.update(userRole);
    }
  }

  public String findRole(Long userId, String objectType, Long objectId) {
    UserRole userRole = userRoleDao.find(userId, objectType, objectId);
    if (userRole == null) {
      return null;
    }
    return userRole.getRole();
  }
}




拦截器的实现拦截器会在 Action 被执行之前被 Struts 2 框架所调用,我们利用这个特性来完成对用户身份的认证,只有用户具有正确角色方能执行 Action 。具体哪些角色可以执行 Action,需要在 Struts 2 的配置文件中指定,将在下一小节中详细阐述。这一点和 Struts 2 内置的 RolesInterceptor 类似,但我们的拦截器可以通过 objectType 和 objectId 来实现更加细粒度的认证。
要创建一个用于用户角色认证的拦截器。需要让其实现 com.opensymphony.xwork2.interceptor.Interceptor 接口并对 String intercept(ActionInvocation actionInvocation) throws Exception 方法进行实现。 如清单 6 。成员变量 roleService 是通过 Spring 的依赖注入被赋予 RoleServiceImpl 。 allowedRoles 和 disallowedRoles 分别存储了允许和不允许执行 Action 的角色,两者不能同时存在。 objectType 和 objectIdKey 分别表示资源的类型和资源 ID 在 HTTP 请求中的参数名。它们是做为 Interceptor 的参数在 Struts 2 配置文件中进行设置,会自动由 Struts 2 框架填充进来。
清单 6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class RBACInterceptor implements Interceptor {
   public static final String FORBIDDEN = "forbidden";
   private List<String> allowedRoles = new ArrayList<String>();
   private List<String> disallowedRoles = new ArrayList<String>();
   private RoleService roleService;
   private String objectType;
   private String objectIdKey;   
     
   public void setRoleService(RoleService roleService) {
  this.roleService = roleService;
   }

   public void setObjectType(String objectType) {
    this.objectType = objectType;
  }
  public void setObjectIdKey(String objectIdKey) {
    this.objectIdKey = objectIdKey;
  }

  public void setAllowedRoles(String roles) {
    if (roles != null)
      allowedRoles = Arrays.asList(roles.split("[ ]*,[ ]*"));
  }

  public void setDisallowedRoles(String roles) {
    if (roles != null)
      disallowedRoles = Arrays.asList(roles.split("[ ]*,[ ]*"));
  }

  public void init() {
  }
     
  public void destroy() {
  }
     
  public String intercept(ActionInvocation actionInvocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    // Get object id
    Long objectId = Long.valueOf(request.getParameter(objectIdKey));
    Map session = actionInvocation.getInvocationContext().getSession();
    // Get current user id
    Long userId = (Long) session.get(Constant.KEY_CURRENT_USER);
    // Get the user role
    String userRole = roleService.findRole(userId, objectType, objectId);

    if (!isAllowed(userRole)) {
      // forbid invoking the action
      return FORBIDDEN;
    } else {
      // allow invoking the action
      return actionInvocation.invoke();
    }
  }

  // Check if the current user has correct role to invoke the action
  protected boolean isAllowed(String userRole) {
    if (allowedRoles.size() > 0) {
      if (userRole == null)
        return false;
      return allowedRoles.contains(userRole);
    } else if (disallowedRoles.size() > 0) {
      if (userRole == null)
        return true;
      return !disallowedRoles.contains(userRole);
    }
    return true;
  }
}




在 intercept 方法中我们根据当前用户的 ID,HTTP 请求参数中获得资源的 ID,所存取的资源类型来调用 RoleService 获得用户的角色。 然后再判断该角色是否在 allowedRoles 和 disallowedRoles 中来确定用户是否有权限调用 Action 。如果用户没权限,则将请求发送到名为“forbidden”的 result 。从这里可以看出,用户的角色验证与身份验证的作用完全不同。身份验证是验证用户是否网站注册用户,而角色认证是在用户为注册用户的前提下对用户相对于站内各种资源扮演的角色的辨别。
上面代码中用到了判断用户是否具有运行 Action 所要求的角色的函数 isAllowed()。它首先根据用户 ID 和 Action 作用于的对象的类型和 ID 从数据库查询到用户对应的角色,然后将用户角色与允许角色的列表逐个比较。如果允许角色列表包含用户实际角色则返回真,否则返回假;如果允许角色列表为空,则将用户角色与禁止角色的列表比较,如果用户的角色被禁止,则返回假,否则返回真。如果两个列表都为空,也返回真。这样既可以对某个 Action 配置允许访问角色列表,也可以配置拒绝访问列表。
使用首先我需要在 Spring 的配置文件中添加系统中所涉及到各个 POJO,如清单 7 。
清单 7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- Data Access Objects -->
  <bean id="userRoleDao" class="com.sample.security.dao.impl.UserRoleDaoImpl"/>
   
  <!-- Service Objects -->
  <bean id="roleService"
    class="com. sample.security.service.impl.RoleServiceImpl" >
    <property name="userRoleDao" ref="userRoleDao" />
  </bean>
   
  <!-- Interceptor Objects -->
  <bean id="RBACInterceptor" scope="prototype"
    class="com. sample.security.interceptor. RBACInterceptor ">
    <property name="roleService"  ref="roleService" />
  </bean>




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




现在我们可以将 RBAC 拦截器添加到任意的 interceptor-stack 中,或者直接配置到任意的 Action 。添加下面清单中的内容到 Struts 2 配置文件中,将能够对在一个日程表中删除会议进行控制。
清单 8
1
2
3
4
5
6
7
8
9
10
<action name="deleteMeeting" class="com.demo.action.DeleteMeetingAction">
<result>/WEB-INF/jsp/deleteMeetingResult.jsp</result>
<result name="forbidden">/WEB-INF/jsp/forbidden.jsp</result>
    <interceptor-ref name="RBAC">
        <param name="allowedRoles">admin, owner</param>
        <param name="objectType">calendar</param>
<param name="objectIdKey">id</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
</action>




至于用户角色的分配,我们可以定义一个 Action 通过 RoleService 来创建。如下面清单 9 的配置和清单 10 的代码实现了一个 Action 允许日程表的创建者来分配角色给其它人。
清单 9
1
2
3
4
5
6
7
8
9
10
<action name="assignCalendarRole" class="com.demo.action.AssignCalendarRoleAction">
<result>/WEB-INF/jsp/deleteMeetingResult.jsp</result>
<result name="forbidden">/WEB-INF/jsp/forbidden.jsp</result>
    <interceptor-ref name="RBAC">
        <param name="allowedRoles">owner</param>
        <param name="objectType">calendar</param>
<param name="objectIdKey">id</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
</action>




清单 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class AssignCalendarRoleAction extends ActionSupport {
  private RoleService roleService;
  private Long userId = 0;
  private String userRole = "reader";
private Long id = 0;

  public AssignCalendarRoleAction (RoleService roleService) {
    this.roleService = roleService;
  }

public String execute() {
roleService.setUserRole(userId, userRole, "calendar", id);
return SUCCESS;
  }
}

返回列表