Add `before` filter for static files in SparkJava
Asked Answered
P

1

9

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?

Pantaloons answered 1/7, 2016 at 22:47 Comment(3)
Hi , same question, seams spark must use serverside template engine(like freemarker). Did you solve it?Whippoorwill
No, unfortunately I haven't solved it.Pantaloons
Trace the source(spark 2.5) : spark.http.matching.MatcherFilter.doFilter, move line 90( // handle static resources) to line 128 (after BeforeFilters.execute(context);), may solve this problem. (But i didn't try yet..., because now i decide to use a template engine: thymeleaf.)Whippoorwill
A
11

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 :)

Azotemia answered 14/12, 2016 at 21:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.