Adding a HTTP interceptor for static resources to Quarkus (with Kotlin) application

129 views Asked by At

I'd like to know how to add a HTTP filter/interceptor for static resources in my quarkus application. I have some static resources which I'd like to serve from my backend with cookie based authentication. I'm noticing that the static resources are being served by Quarkus before hitting the JAS-RX APIs with @Path annotation. I'm not sure if Quarkas has its under lying ways to map static resources first.

Here's an example URL to the resource I'm hitting : http://localhost:8080/books/examplediary/chapter1.html

Here's the filter which I tried using but it isn't intercepting the HTTP request

@Provider
**class CookieValidationFilter : ContainerRequestFilter** {

    @ServerRequestFilter
    **override fun filter(requestContext: ContainerRequestContext)** {
        // Check if the request path matches the static resource path
        val requestPath = requestContext.uriInfo.path

        **println("Request path is $requestPath")**

        if (requestPath == "/books/examplediary/") {
            // Check if the "your_cookie_name" cookie is present
            val cookies = requestContext.cookies
            val cookie = cookies["your_cookie_name"]

            if (cookie == null) {
                // If the cookie is not present, return a 403 Forbidden response
                requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity("Access denied").build())
            }
        }
    }
}

The debug print in the filter doesn't show paths of static resources. I'm able to see other APIs being hit though.

I would like to know if there are ways around this in Quarkus (with Kotlin). Thanks in advance!

1

There are 1 answers

1
geoand On

Serving static resources in Quarkus is done via the low level Vert.x layer, not the the higher JAX-RS / Jakarta REST level.

The easiest way to intercept all HTTP request (including HTTP requests for static resources) is to use the quarkus-reactive-routes extension and adding something like:

import io.vertx.ext.web.RoutingContext;

public class MyFilters {

    @RouteFilter(100) 
    void myFilter(RoutingContext rc) {
       // do something here

       // make sure the rest of the request processing handling code is invoked if  you don't want to abort it
       rc.next(); 
    }
}

You can read more here.