Search code examples
javaspark-java

Add `before` filter for static files in SparkJava


I have specified a location for static files in a Spark application:

Spark.staticFileLocation("/public")

Now I want to add a filter for some files (e.g. for security purposes), but it does not work:

Spark.before("/admin.html", myFilter);

It does work, however, for non-static mappings. Is it possible to configure such a filter for static files as well?

In other words, what are the best practices for Spark to protect static files (like templates for admin pages) from being exposed without authentication?


Solution

  • You can use Spark's StaticFilesConfiguration, just don't use the built-in wiring. Spark.staticFileLocation("/public") creates and sends a response before any other filters or routes are checked. Try this instead:

    package web;
    
    import spark.Service;
    import spark.staticfiles.StaticFilesConfiguration;
    
    public class ServerExample {
    
        public ServerExample() {
            Service service = Service.ignite();
            service.port(1234);
    
            // All other filters first
            service.before((request, response) -> { /* Authentication filter */ });
            service.before("/admin.html", (request, response) ->
                    service.halt(401, "Nothing to see here"));
            service.before((request, response) -> { /* Some other filter */ });
    
            // Static files filter is LAST
            StaticFilesConfiguration staticHandler = new StaticFilesConfiguration();
            staticHandler.configure("/public");
            service.before((request, response) ->
                    staticHandler.consume(request.raw(), response.raw()));
    
            // All your routes (are belong to us)
            service.get("/", (req, res) -> "Hello world");
            service.get("/health", (req, res) -> "Peachy");
        }
    
        public static void main(String[] args) {
            new ServerExample();
        }
    }
    

    Long term, you probably want to serve static files from Nginx or Apache, and if you are really successful, a CDN :)