Performing Server Side Permission Checks in Struts using Java 5 Annotations – Part 3

In part 2 we outlined the annotations and enums were going to use to store our permission data. Applying a permission annotation to a dispatch method looks like this.

@Permissions(operation = Operation.OR, permissions = {
@Permission(permissionKey = RequiredPermissions.VIEW_INVENTORY,
permissionType = PermissionType.SERVER),
@Permission(permissionKey = RequiredPermissions.CONFIGURE_INVENTORY,
permissionType = PermissionType.SERVER)
})
public ActionForward view(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

Now in our BaseAction class we override the dispatchMethod function and call our permission processing method before we call our dispatch


  public BaseAction() {

 @Override
  protected ActionForward dispatchMethod(final ActionMapping mapping,
                                         final ActionForm form,
                                         final HttpServletRequest request,
                                         final HttpServletResponse response,
                                         final String name) throws Exception {

     if (hasPermissions(request, name) == false) {
       return mapping.findForward(NO_PERMISSIONS_ERROR);
    }

    ...etc..

    private boolean hasPermissions(HttpServletRequest request, String name) {

    try {
      Method method = getMethod(name);
      if (method.isAnnotationPresent(Permissions.class)) {
        Permissions allPermissions = method.getAnnotation(Permissions.class);
        return PermissionProcessor.hasPermission(allPermissions, request);
      }
    } catch (Exception ex) {
      log.debug("exception caught in hasPermissions: " + ex);
    }
    return false;
  }

Our PermissionProcessor class looks at the annotations and performs our security checks. I am not going to outline it here because it is a significant amount of code, but basically it processes the annotation, looking at the Operation enum and determining if it needs to AND or OR the enclosed permissions, retrieves any data parameters from the request (using the guidParameter if necessary) and grabs the user context data from the session, finally it performs the actual permission checks that are defined in the permissionKey fields against the specific context data supplied for this request. If the user has the required permissions the dispatch is then called and normal execution of the action ensues, if the PermissionProcessor returns false we call

       return mapping.findForward(NO_PERMISSIONS_ERROR);

and forward the user to a predefined error page that says “missing required permissions to view this page”

This entry was posted in Java, Programming, Struts. Bookmark the permalink.

Comments are closed.