vivekj
vivekj

Reputation: 101

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.

Upvotes: 10

Views: 4591

Answers (1)

Alden
Alden

Reputation: 6703

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
    }
}

Upvotes: 12

Related Questions