Does a servlet filter know the destination of a REST request?

Inside a javax servlet filter, is there a way to know to which servlet where the request is going?

I have some REST resource methods, annotated with JAX-RS (@Path, @GET and so forth), and scanned by RESTEasy.

There is a servlet filter checking the user's permissions for each request, but I would like to differentiate between the REST resources. (They should require different priviledges.)

Is the resource method, for which the REST request is bound, known at this stage? Or is it only matched once the request reaches the servlet behind the filter?

Thanks!

Upvotes: 2

Views: 1192

Answers (3)

ACV
ACV

Reputation: 10561

You can achieve this at least in 3 ways:

  1. By means of web.xml
  2. By accessing SecurityContext in the filter
  3. By annotations javax.annotation.security

All details can be found here: Jersey Security doc

Upvotes: 0

shahshi15
shahshi15

Reputation: 2987

You can achieve this by using ContainerRequestFilter if you'd really like to have some authorization related business logic. You can have something as follows:

public void filter(ContainerRequestContext crc) throws IOException {
        List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates();
        String method = crc.getMethod().toLowerCase();
        String pathTemplate = "";
        String curTemplate = "";
        for (UriTemplate template : matchedTemplates) {
            String templateString = template.getTemplate();
            if (template.endsWithSlash()) {
                curTemplate = templateString.substring(0, templateString.length() - 1);
            }
            else {
                curTemplate = templateString;
            }
            pathTemplate = curTemplate + pathTemplate;
        }
   // Your authorization logic here once you have the pathTemplate.
   // pathTemplate (/v1/users/{userId}/cars/{carId}) and the HTTP method 
   // (GET, PUT..) together will determine the choice of servlet 
   // (resource) and the method within to be chosen and invoked.
}

You can now do your authorization check based on the authorization token (or whatever else you are using for user identification), method called (GET/PUT/POST/DELETE) and the pathTemplate matched. If you designed your paths (pathTemplates) correctly for all resources (in other words if you have "scoped" your paths correctly), some regex magic, and you should have no problems matching user's authorization to a specific url scope. For example: userA with token abc can only access /v1/users/abc/* path while userB with token pqr can only access /v1/users/pqr/cars/*

Don't forget to register it as a jersey resource/filter. In dropwizard we normally do it as:

environment.jersey().register(ApiRequestsFilter.class);

I hope this helps

Upvotes: 1

Andreas
Andreas

Reputation: 159096

No.

The only information available is the request url (path).

Upvotes: 0

Related Questions