SpringBoot configures Cors to solve cross domain requests

1, Introduction to homology strategy

The same origin policy is a security function of the browser. Client scripts from different sources cannot read or write to each other's resources without explicit authorization. Homology policy is the cornerstone of browser security.

What is the source

The source [origin] is the protocol, domain name and port number. For example: http://www.baidu.com:80 This URL.

What is homology

If the protocol, domain name and port number in the address are the same, it belongs to homology.

Judgment of homology

For example, determine whether the following URL is consistent with http://www.a.com/test/index.html Homology

Which operations are not restricted by the same origin policy

  1. Links, redirects and form submission in the page will not be restricted by the same origin policy;
  2. The introduction of cross domain resources is possible. However, JS cannot read or write the loaded content. Such as < script SRC = "..." > embedded in the page</ Script >, < img >, < link >, < iframe >, etc.

Cross domain

Affected by the browser homology strategy mentioned above, scripts that are not homologous cannot operate objects under other sources. If you want to operate an object under another source, you need to cross domain. Under the restriction of homology policy, non homologous websites cannot send AJAX requests.

How to cross domain

  • Descending domain

    You can set "document" Damain ='a.com ', the browser will think they are all the same source. To realize the communication between any two pages above, both pages must be set with document damain='a.com'.

  • JSONP cross domain

  • CORS cross domain

2, Introduction to CORS

In order to solve the problem of browser homology, W3C # proposed cross source resource sharing, namely # CORS( Cross-Origin Resource Sharing).

CORS # achieves the following two points:

  • There are rules without destruction
  • The server implements the CORS interface and can communicate across sources

Based on these two points, CORS # divides requests into two categories: simple requests and non simple requests.

1. Simple request

Before the emergence of CORS, when sending an HTTP request, the header information cannot contain any custom fields, and the HTTP header information does not exceed the following fields:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content type is limited to [application/x-www-form-urlencoded, multipart / form data, text/plain] types

A simple request example:

GET /test HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Origin: http://www.examples.com
Host: www.examples.com

For simple requests, CORS's strategy is to add an Origin field in the request header when requesting. After receiving the request, the server determines whether to allow the request to access according to this field.

  1. If allowed, add the "access control allow origin" field in the HTTP header and return the correct result;
  2. If it is not allowed, the "access control allow origin" field will not be added to the HTTP header.

In addition to the "access control allow origin" mentioned above, there are several fields to describe the "CORS" returned results:

  1. Access control allow credentials: optional, whether the user can send and process cookie s;
  2. Access control expose headers: optional, which allows users to get the fields. Several fields can be obtained whether they are set or not, including cache control, content language, content type, Expires, last modified and Pragma.

2. Non simple request

For cross source requests that are not simple requests, the browser will add an OPTION request before the real request is sent, which is called preflight request. The pre check request adds the information of the real request, including the request method, custom header field and source information, to the HTTP header field, and asks the server whether to allow such operations.

For example, a DELETE request:

OPTIONS /test HTTP/1.1
Origin: http://www.examples.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: X-Custom-Header
Host: www.examples.com

Fields related to CORS include:

  1. HTTP # method used for the request # access control request method;
  2. The custom header field contained in the request is access control request headers.

When the server receives the request, it needs to verify the # Origin, access control request method and access control request headers # respectively. After passing the verification, it will add the following to the HTTP header information returned:

Access-Control-Allow-Origin: http://www.examples.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 1728000

Their meanings are:

  1. Access control allow methods: methods allowed by real request
  2. Access control allow headers: fields allowed by the server
  3. Access control allow credentials: allow users to send and process cookie s
  4. Access control Max age: the validity period of the pre inspection request, in seconds. Within the validity period, the pre inspection request will not be sent repeatedly

When the pre check request passes, the browser will send a real request to the server. This enables cross source requests.

3, Configuring CORS with Spring Boot

1. Implemented with @ CrossOrigin annotation

#If you want to configure @ CrossOrigin @ CORS for an interface, you can add @ CrossOrigin @ annotation on the method:

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
    return "{\"project\":\"just a test\"}";
}

#If you want to add CORS configuration to a series of interfaces, you can add annotations on the class and declare that all interfaces are valid for this class:

@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
    
}

#If you want to add a global configuration, you need to add a configuration class:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}

In addition, you can configure CORS rules by adding a Filter and manually specify which interfaces are valid.

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);	config.addAllowedOrigin("http://localhost:9000");
    config.addAllowedOrigin("null");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config); // CORS configuration is valid for all interfaces
    FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

2. Principle analysis

No matter how you configure CORS, you are actually constructing CorsConfiguration. A CORS configuration is represented by a CorsConfiguration class. Its definition is as follows:

public class CorsConfiguration {
    private List<String> allowedOrigins;
    private List<String> allowedMethods;
    private List<String> allowedHeaders;
    private List<String> exposedHeaders;
    private Boolean allowCredentials;
    private Long maxAge;
}

The verification of CORS rules in Spring is implemented by delegating to DefaultCorsProcessor.

The process of DefaultCorsProcessor is as follows:

  1. The judgment is based on whether the Header contains Origin. If yes, it means CORS request, go to 2; Otherwise, it indicates that it is not a CORS request and will not be processed.
  2. Judge whether the Header of the # response # has included # access control allow origin. If so, it proves that it has been processed. Go to 3, otherwise it will not be processed.
  3. Judge whether it is homologous. If so, it will be transferred to the class responsible for the request for processing
  4. Whether the CORS rule is configured. If it is not configured and is a pre inspection request, the request will be rejected. If it is not configured and is not a pre inspection request, it will be handed over to the class responsible for the request for processing. If configured, the request is verified.

Verification is based on the configuration of CorsConfiguration:

  1. Judge whether , origin , is legal
  2. Judge whether the method is legal
  3. Determine whether the header is legal
  4. If all of them are legal, add the response field in the response header and give it to the class responsible for the request for processing. If they are not legal, reject the request.

Keywords: Java Javascript Spring Boot

Added by greenday on Thu, 27 Jan 2022 03:21:35 +0200