Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i convince spring 4.2 to pass OPTIONS request through to the controller

we have are using spring mvc with @RestController annotations on our controllers, and we're handling authorization in the controller. we use the same code to set the allowed methods in responses to CORS pre-flight request. to achieve this, we have:

    <init-param>
        <param-name>dispatchOptionsRequest</param-name>
        <param-value>true</param-value>
    </init-param>

in the configuration of the dispatcher servlet, and then we have:

    @RequestMapping(value="/some/collections", method=RequestMethod.OPTIONS)
    public void collectionOptions(
            HttpServletRequest req,
            HttpServletResponse res) {
        List<RequestMethod> methods = new ArrayList<>();
        // check actual permissions, add the appropriate methods
        CORS.setAllowedMethodHeaders(res,methods);
    }

we also have an interceptor that do basic checks on CORS pre-flight to see if the origin can possibly have any permissions at all.

we do it like this mostly because permissions for some requests actually depend on @RequestParams, i.e.:

    OPTIONS /api/collections?userId=122

might be allowed if you have administrative privileges OR you actually the user with the ID 122. also, we have API keys, so

    OPTIONS /api/collections?userId=122&apiKey=ABC

might be OK for one origin, but not for another one.

this works fine, but spring 4.2 now decides wether or not it handles an OPTIONS request, via a call to:

    CorsUtils.isCorsRequest(request);

in AbstractHandlerMapping and then returns

        HandlerInterceptor[] interceptors = chain.getInterceptors();
        chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);

instead of the HandlerMethod ...

what we would need is some way to tell spring to let the controller handle OPTIONS requests, no matter what preflight request handlers are present.

We don't seem to be able to find a point where we can EITHER tell the built-in CORS handling to be quiet or to configure some subclass somewhere that would allow us to bypass the newly added code in:

  AbstractHandlerMapping.getHandler(HSR request)

Is this in any way possible? Wouldn't it be nice for a feature like this to be quiet until I actively enable it (through WebMvcConfigurerAdapter or via those @CrossOrigin annotations)?

-------- EDIT -------------

the HTTP standard says the following about the OPTIONS method:

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

thinking beyong just CORS, i think that intercepting a CORS options call although a corresponding method is mapped on the controller is not the right way to go. yes, CORS is one thing you can do with an OPTIONS call. but it is by no means the only one.

if there is nothing mapped and if a handler method is mapped with a different request method and the @CrossOrigin annotation, the assumptions that i want the built in CORS support to be triggered would be fine, but i do not think that any request that has the origin header set should automatically ONLY go to the CORS handlers.

like image 668
rmalchow Avatar asked Mar 14 '16 08:03

rmalchow


2 Answers

I just convinced Spring 4.3 to pass CORS preflights to my controller by adding a custom handler mapping:

public class CorsNoopHandlerMapping extends RequestMappingHandlerMapping {

    public CorsNoopHandlerMapping() {
        setOrder(0);  // Make it override the default handler mapping.
    }

    @Override
    protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request,
             HandlerExecutionChain chain, CorsConfiguration config) {
        return chain;  // Return the same chain it uses for everything else.
    }
}

Note: you'll still need to tell Spring to dispatch OPTIONS requests to your controller to begin with - that is, set dispatchOptionsRequest to true in dispatcherServlet like it says in this question.

WHY IT WORKS

Sébastien's above answer suggests using your own CorsProcessor. As far as I can tell, this will still not use your controller as the handler; it will just pass a different CorsProcessor to its own CORS handler.

By default, it looks like the method AbstractHandlerMapping#getCorsHandlerExecutionChain will throw out your controller when it detects a preflight. Instead of using your controller as the handler, it instantiates a new PreFlightHandler and uses that instead. See Spring source code. This is the problematic line:

chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);

What it's doing here is rebuilding the execution chain with a PreFlightHandler instead of your controller. This is not what we want, so we can override it to return the input chain.

like image 147
maybe not Avatar answered Oct 25 '22 02:10

maybe not


As suggested by zeroflagl, I also think that this is not a good idea to mix access control and CORS. And you should keep in mind that only preflight CORS requests are OPTIONS ones.

If you need to customize Spring CORS handling, you can use AbstractHandlerMapping#setCorsProcessor() to provide your own implementation that could eventually extend DefaultCorsProcessor.

Please notice that by default, CORS processing is enabled but no remote origin is allowed so customizing CorsProcessor is rarely needed. More info on this blog post.

Your access control check could be done as a regular HandlerInterceptor since a successful CORS preflight request will be followed by an actual request.

like image 43
Sébastien Deleuze Avatar answered Oct 25 '22 03:10

Sébastien Deleuze