Friday, March 25, 2011

Log in Sling

The default Sling user is anonymous and it has read-only access to the repository. So if this user attempts to change anything in the repository he gets an error like this

javax.jcr.AccessDeniedException: <path>: not allowed to add or modify item

So in order to change the data they have to login with a user that has proper permissions. But we still want to allow anonymous visitors to read the content of our site (like search engines). We ask them to log in only if they choose to edit the content. One way to do this in Sling is like this:

if (!currentSession.hasPermission(currentNode.path, "set_property"))
    response.sendRedirect(request.requestURL + "?sling:authRequestLogin=BASIC");


Put this code at the beginning of an ESP page that performs content changes.