Search code examples
quarkus

How can I add an http interceptor to a Quarkus application?


I would like to add an HTTP interceptor to my Quarkus application so I can intercept all HTTP requests. How can such that be achieved?


Solution

  • Quarkus uses RESTEasy as its JAX-RS engine. That means that you can take advantage of all of RESTEasy's features, including Filters and Interceptors.

    For example to create a very simple security mechanism, all you would need to do is add code like the following:

    @Provider
    public class SecurityInterceptor implements ContainerRequestFilter {
        @Override
        public void filter(ContainerRequestContext context) {
            if ("/secret".equals(context.getUriInfo().getPath())) {
              
      context.abortWith(Response.accepted("forbidden!").build());
            }
        }
    }
    

    It should be noted that this only works for requests that are handled by JAX-RS in Quarkus. If the requests are handled by pure Vert.x or Undertow, the filtering mechanisms of those stacks will need to be used.

    UPDATE

    When using RESTEasy Reactive with Quarkus, the @ServerRequestFilter annotation can be used instead of implementing ContainerRequestFilter. See this for more information

    class Filters {
    
        @ServerRequestFilter(preMatching = true)
        public void preMatchingFilter(ContainerRequestContext requestContext) {
            // make sure we don't lose cheese lovers
            if("yes".equals(requestContext.getHeaderString("Cheese"))) {
                requestContext.setRequestUri(URI.create("/cheese"));
            }
        }
    
        @ServerRequestFilter
        public Optional<RestResponse<Void>> getFilter(ContainerRequestContext ctx) {
            // only allow GET methods for now
            if(ctx.getMethod().equals(HttpMethod.GET)) {
                return Optional.of(RestResponse.status(Response.Status.METHOD_NOT_ALLOWED));
            }
            return Optional.empty();
        }
    }