Multiple container filter for jersey

We plan to use the use of Jersey links for our REST APIs. As a prototype, I also played with ContainerRequestFilters, and I implemented several of them. Is there a way we can control the execution order of these filters?

The scenario that I am considering here is to provide the first security filter, and if necessary set the SecurityContext and then execute the other filters.

+7
java-ee rest jersey
source share
1 answer

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

  • Registration filter always starts first
  • The authentication filter should run as follows
  • The authorization filter should work as follows
  • Custom filter should always run after others

You can 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 } } 
+8
source share

All Articles