Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get path param from ContainerRequestContext

I want to apply authorization filter for my REST API endpoint, and the filter need path parameter to do the filtering. here is my endpoint and code:

endpoint:

curl --url 'localhost:80/reports/resources/org/12345/product/111 ' --request GET --header 'Authorization: <token here>'

resource code:

@Path("/resources")
public class MyResource extends AbstractResource {
...
    @GET
    @Path("/org/{orgId}/product/{productId}")
    @Produces(MediaType.APPLICATION_JSON)
    @RoleAuthenticated
    public Response getResourcesReport(@PathParam("orgId") String orgId,
                                       @PathParam("productId") String productId,
                                       @Context HttpHeaders headers){....}

Filter:

@PreMatching
@RoleAuthenticated
public class AuthorizationFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
            MultivaluedMap<String, String> pathparam = requestContext.getUriInfo().getPathParameters();   <--  return empty map  
}

I was expecting requestContext.getUriInfo().getPathParameters() returned map of the following:

orgId 12345
productId 111

how come it return an empty map ? and How can I get path parameters from ContainerRequestContext?

like image 694
user468587 Avatar asked Feb 05 '16 00:02

user468587


1 Answers

You used a @PreMatching annotation on the filter.

The Javadoc says:

In case the filter should be applied at the pre-match extension point, i.e. before any request matching has been performed by JAX-RS runtime, the filter MUST be annotated with a @PreMatching annotation.

So the filter is invoked before the incoming request has been matched to a particular resource by the JAX-RS runtime, and therefore the path parameters are empty.

So I guess you need to remove the @PreMatching annotation.

like image 118
wero Avatar answered Sep 28 '22 02:09

wero