Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ContainerRequestFilter for Jersey

We are planning on using Jersey's reference implementation for our REST APIs. As a prototype effort, I was also playing around with the ContainerRequestFilters and I implemented multiple of them. Is there a way in which we can control the order in which these filters are executed?

The scenario that I am thinking over here is to ensure that the security filter must be the first one to run, and if required establish the SecurityContext and then execute other filters.

like image 574
vivekj Avatar asked Dec 12 '13 22:12

vivekj


1 Answers

Yes you can control this with the javax.annotation.Priority attribute and the default javax.ws.rs.Priorities. For example if you wanted:

  1. Logging filter always runs first
  2. Authentication filter should run next
  3. Authorization filter should run next
  4. Custom filter should always run after others

You could do:

@Priority(Integer.MIN_VALUE)
public class CustomLoggingFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        // DO LOGGING HERE, THIS RUNS FIRST
    }
}

@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        String authHeader = requestContext.getHeaderString(HttpHeaders.WWW_AUTHENTICATE);

        // DO AUTHENTICATION HERE, THIS RUNS SECOND
    }
}

@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // DO AUTHORIZATION HERE, THIS RUNS THIRD
    }
}

@Priority(Priorities.USER)
public class MyAwesomeStuffFilter implements ContainerRequestFilter
{
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException
    {
        // DO AWESOME STUFF HERE, THIS RUNS LAST
    }
}
like image 100
Alden Avatar answered Nov 16 '22 03:11

Alden