perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.64k stars 1.56k forks source link

Redirect causing filter to execute twice #982

Closed Nath5 closed 5 years ago

Nath5 commented 6 years ago

I am tying to use a before filter to add trailing slashes as well as a before filter to handle authentication on certain endpoint.

Here is my routing code:

// Add filter to all requests which adds a trailing slash if it is missing //
before("*", Filters.addTrailingSlashes);
path("/api", () -> {
    // Authentication Intercept //
    before("/*", AuthenticationIntercept.authenticationIntercept);

    // Sampling Endpoints //
    get(Path.Web.SAMPLES_FETCH_LATEST, SamplingController.fetchLatestSamples, new JsonTransformer());
    get(Path.Web.SAMPLES_FETCH_FOR_DEVICE, SamplingController.getLatestSamplesForDevice, new JsonTransformer());
});

I then hit the following endpoint:

localhost:4567/api/samples/10

What happens is that the addTrailingSlashes gets called first. Then the authentication Filter gets called, then the addTrailingSlashes gets called again this time with localhost:4567/api/samples/10/ as the request endpoint and finally the authentication filter gets called again.

Is this the correct behavior. What I want to happen is that the addTrailingSlashes gets called once adds the slash and then forwards the request one time so that the authentication filter gets called only once.

Any ideas would be most appreciated.

Thanks, Nathan

tipsy commented 5 years ago

Yes, it's the correct behavior. You have a filter running before every request, and you're redirecting one request to a different endpoint (which makes it a new request).