Spring Boot Road Primer (8) --- solve cross-domain problems in Spring Boot

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/100165247

Before talking about cross-domain problems in Spring Boot, I think we need to first understand the same origin policy

1 Same Origin Policy

The client script different sources in the absence of express authorization, can not read and write other resources. The strategy is the cornerstone of browser security.

Maybe everyone was wondering, what is the '' source '? What is "homologous"? In fact, the source can be understood as a combination of protocol, domain name and port number, and homologous refers to the address of the protocol, the domain name and port number are the same.

Due to the browser same-origin policy, the script is not homologous to other sources can not operate the following objects can not send AJAX requests between non-homologous sites. Want another source in the operation target requires cross-domain, which can be divided into cross-domain and cross-domain JSONP CORS cross-domain.

2 JSONP cross-domain and cross-domain CORS

CORS, namely Cross-Origin Resource Sharing, Chinese meant for shared resources across domains. It defines how the browser and server resources in the cross-domain access communication.

CROS is now mainstream solve the problem of cross-domain programs, the difference between it and JSONP as follows:

  1. JSONP GET request can only be achieved, while CORS support all types of HTTP requests.
  2. Use CORS, developers can use to initiate a normal XMLHttpRequest request and obtain data than JSONP have better error handling.
  3. JSONP primarily to support older browsers, they often do not support CORS, while the vast majority of modern browsers already support CORS.

Overall, CORS compared with JSONP, more advanced, convenient and reliable.

3 CORS cross-domain Introduction

CORS requests into two categories: simple and non-simple request request.

Simple request

The following is a simple example:

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

For a simple request, CORS strategy is to add a Origin request header field in the request, the server receives the request, according to the field determines whether to permit the access request. If allowed, then add the information in the HTTP header Access-Control-Allow-Origin field, and returns the correct result, it would not add Access-Control-Allow-Origin field in the HTTP header.

Non-simple request

For cross-origin requests are not simple request, the browser will request before the real issue, increase the time OPTION request, called a preflight request. Real preflight request information request includes a request method, custom header field, a source of information to the HTTP header information field, asks the server whether to allow such operations. Examples are as follows:

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

When the server receives a request, it is necessary to separately Origin, Access-Control-Request-Method (using HTTP request method), Access-Control-Request-Headers (custom request header field included) for authentication, authentication is passed, in return will add HTTP header information:

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

Its meaning is:

  1. Access-Control-Allow-Methods: Method of real requests permission
  2. Access-Control-Allow-Headers: server allows the use of field
  3. Access-Control-Allow-Credentials: whether to allow users to send, cookie handling
  4. Access-Control-Max-Age: Validity of the preflight request, in seconds. Within the validity period, the request will not be sent preflight

After the pre-screening requests through the browser sends a request to the real server. This enables cross-origin requests.

Analog cross-domain request 4

Let us not use CORS, see what will happen next?

We have established two Spring Boot, named test and demo.

test project controller:

package edu.szu.test.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

	@RequestMapping("index")
    public String index(){
        return "index" ;
	}
}

application.properties:

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp
# 指定端口
server.port=8080

test/src/main/webapp/WEB-INF/jsp/index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello 8080!
</body>
</html>

demo project controller:

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {

	@RequestMapping("/index")
    public String index(){
        return "index" ;
	}
}

application.properties:

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp
# 指定端口
server.port=8087

demo/src/main/webapp/WEB-INF/jsp/index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
Hello 8087!
<input type="button" value="commit" onclick="test()"/>
</body>
<script type="text/javascript">
    function test(){
        $.ajax({
            url:'http://localhost:8080/index',
            type:'post',
            dataType:'text',
            success:function(data){
                console.log(data);
            }
        });
    }
</script>
</html>

Run test and demo projects started two classes, the browser to http: // localhost: 8087 / index, find the page has been unable to jump. Open the console and found the following error.

Here Insert Picture Description
Translate, because there is no head header Access-Control-Allow-Origin in the resource request, 8087 this field does not have access, XMLHttpRequest can not load data port 8080.

5 Spring Boot configuration method CORS

Achieved by @CrossOrigin

@CrossOrigin add annotations on methods or classes, CORS can be configured directly.

@Controller
public class IndexController {

	@RequestMapping("index")
	@CrossOrigin("http://localhost:8087")
    public String index(){
        return "index" ;
	}
}

Filter Configuration

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        //是否允许请求带有验证信息
        corsConfiguration.setAllowCredentials(true);
        //允许访问的客户端域名
        corsConfiguration.addAllowedOrigin("*");
        //允许服务端访问的客户端请求头
        corsConfiguration.addAllowedHeader("*");
        //允许访问的方法名,GET POST等
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

The effective way for global configuration.

Configuring interceptors

@Configuration
public class MyConfiguration implements WebMvcConfigurer  {

    @Override  
    public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**")  
                .allowCredentials(true)  
                .allowedHeaders("*")  
                .allowedOrigins("*")  
                .allowedMethods("*");  

    }  
}

The effective way for global configuration.

Reference: SpringBoot Cors configuration problem solving cross-domain requests
CORS solve the problem of cross-domain ajax
Spring Boot 2.0 to solve cross-domain problems SpringBoot2.X
(thirteen): SpringBoot setting supports cross-domain request

Guess you like

Origin blog.csdn.net/Geffin/article/details/100165247