Check a User's Permissions on a Node

Introduction

Goal

Use the JCR API in your HST code to check a certain user's permissions on a certain repository node.

Background

The JCR API provides a way to check whether a user has a certain permission on a certain node through javax.jcr.Session#hasPermission(String, String). This page provides a basic example

Example

The code snippet below shows how to check whether the user "author" has "hippo:admin", "hippo:editor", and "hippo:author" permissions on the node /content/documents/myproject/content/sample-document/sample-document.

To use javax.jcr.Session#hasPermission(String, String), you need to have access to a logged-in JCR session for the relevant user ("author" in the example). The code snippet assumes implementation in HST code and retrieves the repository component through the HST component manager, then logs in as the user "author" to obtain the session. Implementation in CMS code is similar except for the way the repository component is obtained.

String path = "/content/documents/myproject/content/sample-document/sample-document";

Repository repository = HstServices.getComponentManager().getComponent(Repository.class.getName());

try {
    Session session = repository.login(new SimpleCredentials("author", "author".toCharArray()));
    boolean hasPermission = session.hasPermission(path, "hippo:admin");
    System.out.println("hasPermission hippo:admin " + hasPermission);
    hasPermission = session.hasPermission(path, "hippo:editor");
    System.out.println("hasPermission hippo:editor " + hasPermission);
    hasPermission = session.hasPermission(path, "hippo:author");
    System.out.println("hasPermission hippo:author " + hasPermission);
} catch (RepositoryException e) {
    // TODO handle exception
}

In a standard project created using the Maven archetype, the above code snippet produces the following system output:

hasPermission hippo:admin false
hasPermission hippo:editor false
hasPermission hippo:author true
Did you find this page helpful?
How could this documentation serve you better?
On this page
    Did you find this page helpful?
    How could this documentation serve you better?