1

I have some code about Pre-flight Filter in Spring boot, but I don't know the purpose of this code:

@Component
// We want to put this in front of SpringSessionFilter
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, x-auth-token");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if(!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
            try {
                chain.doFilter(req, res);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Pre-fight");
            response.setHeader("Access-Control-Allowed-Methods", "POST, GET, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "authorization, content-type, x-auth-token, " +
                    "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with");
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

And this is the explain for this file:

So when Angular 2 send an http post ajax call, it will first send a pre-flight and method type is not "POST" but "OPTIONS". If this preflight has a valid response, then it will start to send the real http post. This is to prevent cross site attack. At backend, spring doesn't have a out-of-box handling for this. So we need to check whether the http method is a preflight or not. If it is, we will just respond with valid headers and info. If not, we'll just proceed the filter chain.

But I can't understand the source code. Anyone can explain for me?

mrSmith91
  • 338
  • 1
  • 6
  • 18
  • Which part are you having difficulties with? – klorand Jun 30 '19 at 12:31
  • The source code does exactly what you mentioned in above paragraph. It checks if the request type is other than OPTIONS, then proceed to the next filter. If it is an OPTIONS request which would be a pre-flight cors request and hence respond accordingly. This would be required only if the client calling your API is from different origin. Else not required. Read about CORS more to have better understanding. – Manish Bansal Jun 30 '19 at 12:41
  • Can you explain in code? Or explain code line by line? Why we need `HttpServletRequest request = (HttpServletRequest) req;`, what is `response.setHeader("Access-Control-Allow-Origin", "*");` ? What is `FilterChain `? – mrSmith91 Jun 30 '19 at 12:54

1 Answers1

3

Why response.setHeader("Access-Control-Allow-Origin", "*"); ?

Cross-Origin Resource Sharing (CORS) is a security concept that allows restricting the resources implemented in web browsers. It prevents the JavaScript code producing or consuming the requests against different origin.

For example, your web application is running on 8080 port and by using JavaScript you are trying to consuming RESTful web services from 9090 port. Under such situations, you will face the Cross-Origin Resource Sharing security issue on your web browsers. To grant the access you can set it as * or with your domain

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood.

It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.

A preflight request is automatically issued by a browser when needed. In normal cases, front-end developers don't need to craft such requests themselves.

For example, a client might be asking a server if it would allow a DELETE request, before sending a DELETE request, by using a preflight request:

OPTIONS /resource/foo 
Access-Control-Request-Method: DELETE 
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

If the server allows it, then it will respond to the preflight request with an Access-Control-Allow-Methods response header, which lists DELETE:

HTTP/1.1 204 No Content
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400

What is FilterChain?

FilterChain Filters

Romil Patel
  • 12,879
  • 7
  • 47
  • 76