Search code examples
javarestlet

RESTlet Authorization Filter


I am developing a RESTlet API (JAVA), and I've created a custom authorization filter that I run all requests through before passing it to my router. In my requests I always pass the session ID as a request attribute, e.g.

    http://localhost:8080/myAPI/{sid}/someResource/

Now, in my functions that extends ServerResource, I can do something like this to easily extract that {sid}:

    String sid = (getRequestAttributes().containsKey("sid")) ? getRequestAttributes().get("sid").toString() : "";

My problem is, in my authorization function, which extends Filter (the authorization function is not called via a router, but is called in my main createInboundRoot() function), I cannot use the same method to extract the {sid}. I've created a workaround using string manipulation of request.getResourceRef().getSegments(), but there must be a better way?

Any help will be appreciated!

Thanks


Solution

  • You can create a common parent class for any child of ServerResource. like this:

    public class CommonParentResource extends ServerResource
    {
        // class definition
    }
    

    And then override the doInit() method of the ServerResource class in it.

    public class CommonParentResource extends ServerResource
    {
        public void doInit()
        {
            boolean authorized=false;
    
            String sid = getRequestAttributes().containsKey("sid") ? (String)getRequestAttributes().get("sid") : StringUtils.EMPTY;
    
            // Authorization logic here.
    
            if(!authorized)//after authorization process completed.
            {
                getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
                getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);
            }
        }
    }
    

    Now any new child class of ServerResource that you want to perform this authorization check, must extend this CommonParentResource class. Like this:

    public class FriendsListResource extends CommonParentResource
    {
        @Get
        //......
    }
    

    Two points are important here:

    1. doInit() of any child class of ServerResource is called before calling any method annotated with @Get / @Post / ...

    2. (Caution) If you do not use this statement:

      getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
      

      i.e. if you do not set status of response to an error, then methods annotated with @Get / @Post / @Put / ... will get called ! But if your program sets the status of the response to an error-status, then the @Get / @Post / @Put / ... will not get executed, and the end user will see the error message represented by:

      getResponse().setEntity(/*Representation carrrying message for unauthorized user*/);