Quantcast
Channel: Planet Apache
Viewing all articles
Browse latest Browse all 9364

Bertrand Delacretaz: Generating hard to guess content URLs in Sling

$
0
0

In RESTful apps, it is often useful to create hard to guess URLs, as a simple privacy device.

Here’s a self-explaining example (with hardcoded parameters) of how to do that in Sling.

After installing this component, an HTTP POST to a node named ‘foo’ creates a child node with a somewhat long hex string as its name, instead of the usual simple names generated by Sling.

package foo;

import java.util.Random;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.servlets.post.NodeNameGenerator;

/** Example that generates hard-to-guess node names in Sling,
 * for nodes added under nodes named 'foo'
 *
 * To test, build and install a bundle that includes this component,
 * and run
 * <pre>
 *   curl -X MKCOL http://admin:admin@localhost:4502/foo
 *   curl -F title=bar http://admin:admin@localhost:4502/foo/
 * </pre>
 * The output of the second curl call should return something like
 * <pre>
 *   Content created /foo/dd712dd234637bb9a9a3b3a10221eb1f
 * </pre>
 * Which is the path of the created node.
 */
@Component
@Service
public class FooNodeNameGenerator implements NodeNameGenerator {
    private static final Random random = new Random(System.currentTimeMillis());

    /** @inheritDoc */
    public String getNodeName(
            SlingHttpServletRequest request,
            String parentPath,
            boolean requirePrefix,
            NodeNameGenerator defaultNng)
    {
        if(parentPath.endsWith("/foo")) {
            final StringBuilder name = new StringBuilder();
            for(int i=0; i < 2; i++) {
                name.append(Long.toHexString(random.nextLong()));
            }
            return name.toString();
        }
        return null;
    }
}


Viewing all articles
Browse latest Browse all 9364

Trending Articles