Configuring cross domain Cors with SpringBoot

Configuring cross domain Cors with SpringBoot

01. 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: This URL.

What is homology

If the protocol, domain name and port number in the address are the same, they belong to the same source.

Judgment of homology

For example, determine whether the following URL is consistent with Homology

  • Homology
  • Different sources, different domain names
  • Different sources, different protocols
  • Port numbers are different for different sources

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.

02. Cross domain

Affected by the browser homology policy mentioned earlier, 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, AJAX requests cannot be sent between non homologous websites.

03. How to solve cross domain problems

  • Descending domain

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

  • JSONP cross domain

  • CORS cross domain

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

04. Introduction to CORS

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

A simple request example:

GET /test HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br

For simple requests, CORS's policy is to add an Origin field in the request header. 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 information and return the correct result;
  2. If not, the access control allow origin field is not added to the HTTP header.

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

  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 a 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
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: X-Custom-Header

Fields related to CORS are:

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

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

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

They mean:

  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 check request, in seconds. Pre inspection requests will not be sent repeatedly within the validity period

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

05. Configure CORS for Spring Boot

1. Implemented using @ CrossOrigin annotation

#If you want to configure 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 of the class are valid:

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

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

public class WebMvcConfig extends WebMvcConfigurerAdapter {

    public void addCorsMappings(CorsRegistry registry) {
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")

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

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

Keywords: Java Front-end Spring Boot

Added by pwnuspoints on Thu, 13 Jan 2022 07:09:50 +0200