Search code examples
javaauthenticationurirestlet

Restlet - Using URI Template Variables in Authenticator


I am attempting to perform authentication in Restlet where I am looking up credentials based on a portion of the URI, i.e. multitenant authentication.

I have not been able to chain the router for the authenticator to the router for resource access. Is this even possible? Let's say I have an Authenticator that needs the tenantId variable to look up the user. I've been trying a setup like the following to get it to work with no success. Thoughts?

public class MyApplication extends Application
{
    public Authenticator authenticator;

    @Override
    public Restlet createInboundRoot()
    {
        Router router = new Router(getContext());
        router.attach("/", TraceResource.class);
        router.attach("/{apiVersion}/{tenantId}/pathOne/{someId}",
            ResourceOne.class);
        router.attach("/{apiVersion}/{tenantId}/pathTwo/{someId}",
            ResourceTwo.class);

        authenticator.setNext(router);

        Router authenticationRouter = new Router(getContext());
        authenticationRouter.attach("/{apiVersion}/{tenantId}/{remaining}",
            authenticator).setMatchingMode(Template.MODE_STARTS_WITH);

        return authenticationRouter;
    }
}

Solution

  • It's almost correct, here is a fix:

    public class MyApplication extends Application
    {
        public Authenticator authenticator;
    
        @Override
        public Restlet createInboundRoot()
        {
            Router router = new Router(getContext());
            router.attach("/", TraceResource.class);
            router.attach("/pathOne/{someId}", ResourceOne.class);
            router.attach("/pathTwo/{someId}", ResourceTwo.class);
            authenticator.setNext(router);
    
            Router authenticationRouter = new Router(getContext());
            authenticationRouter.attach("/{apiVersion}/{tenantId}",
                authenticator).setMatchingMode(Template.MODE_STARTS_WITH);
    
            return authenticationRouter;
        }
    }