SpringBoot: CORS embodiment handles three cross-domain request

First, the cross-domain background

1.1 What is cross-domain?

UrlThe general format:

Protocol + domain (sub-domain name + main domain name) + port number + Resource Locator

Example:

https://www.dustyblog.cn:8080/say/Hello by 

https + www + dustyblog.cn + 8080 + say / Hello composition

 

composition.

As long as part of the agreement, subdomains main domain name, port number, these four have a different, can be considered different domains, access to resources between different domains with each other, it is called cross-domain.

1.2 a normal request

  • Controller level code:
1 @RequestMapping("/demo")
2 @RestController
3 public class CorsTestController {
4 
5     @GetMapping("/sayHello")
6     public String sayHello() {
7         return "hello world !";
8     }
9 }
  • Start the project, a test request

    Browser opens localhost: 8080 / demo / sayHello

     You can print out "hello world"

1.3 cross-domain test

To Chrome as an example:

  • Open any website, such as: https://blog.csdn.net

  • Press F12, developer tools [open], [inside] Console test js code may be directly input;

var token= "LtSFVqKxvpS1nPARxS2lpUs2Q2IpGstidMrS8zMhNV3rT7RKnhLN6d2FFirkVEzVIeexgEHgI/PtnynGqjZlyGkJa4+zYIXxtDMoK/N+AB6wtsskYXereH3AR8kWErwIRvx+UOFveH3dgmdw1347SYjbL/ilGKX5xkoZCbfb1f0=,LZkg22zbNsUoHAgAUapeBn541X5OHUK7rLVNHsHWDM/BA4DCIP1f/3Bnu4GAElQU6cds/0fg9Li5cSPHe8pyhr1Ii/TNcUYxqHMf9bHyD6ugwOFTfvlmtp6RDopVrpG24RSjJbWy2kUOOjjk5uv6FUTmbrSTVoBEzAXYKZMM2m4=,R4QeD2psvrTr8tkBTjnnfUBw+YR4di+GToGjWYeR7qZk9hldUVLlZUsEEPWjtBpz+UURVmplIn5WM9Ge29ft5aS4oKDdPlIH8kWNIs9Y3r9TgH3MnSUTGrgayaNniY9Ji5wNZiZ9cE2CFzlxoyuZxOcSVfOxUw70ty0ukLVM/78=";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/demo/sayHello');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

 The results show that: the request https://blog.csdn.netrequest failed under the domain name!

Second, the solution - Cors across domains

What is 2.1 Cors

CORS called the Cross Origin Resource Sharing (cross-domain resource sharing), each page needs to return a http head called Access-Control-Allow-Origin allow access to sites outside the domain, you can expose only limited resources and limited domain site access.

 We can understand: if a request need to allow cross-domain access, you need to httpset the header

Access-Control-Allow-Origin to determine which sites need to be allowed access. The assumptions need to allow HTTPS: // request www.dustyblog.c the site of cross-domain, may be provided: 

Access -Control-the Allow-Origin: HTTPS: // www.dustyblog.cn.

2.2 How to solve cross-domain Cors

   2.2.1 Option One: Use @CrossOriginannotations

     In Controlleruse the @CrossOriginnotes, all interfaces in the class are available through cross-domain access

1 @ RequestMapping ( "/ demo2" )
 2  @RestController
 3  // @CrossOrigin // all domain names under the class can access all interfaces 
4 @CrossOrigin ( "https://blog.csdn.net") // only specify a domain name under such access to all interfaces 
. 5  public  class CorsTest2Controller {
 . 6  
. 7      @GetMapping ( "/ the sayHello" )
 . 8      public String the sayHello () {
 . 9          return "Hello World --- 2" ;
 10      }
 . 11 }

   Current specified here CorsTest2Controllerall the ways to handle https://csdn.netthe request on the domain, where you can test:

  • In https://blog.csdn.net open the debug window, enter the page (Note: This address is a request /demo2, please be distinguished from cases in 1.2 /demo)
var token= "LtSFVqKxvpS1nPARxS2lpUs2Q2IpGstidMrS8zMhNV3rT7RKnhLN6d2FFirkVEzVIeexgEHgI/PtnynGqjZlyGkJa4+zYIXxtDMoK/N+AB6wtsskYXereH3AR8kWErwIRvx+UOFveH3dgmdw1347SYjbL/ilGKX5xkoZCbfb1f0=,LZkg22zbNsUoHAgAUapeBn541X5OHUK7rLVNHsHWDM/BA4DCIP1f/3Bnu4GAElQU6cds/0fg9Li5cSPHe8pyhr1Ii/TNcUYxqHMf9bHyD6ugwOFTfvlmtp6RDopVrpG24RSjJbWy2kUOOjjk5uv6FUTmbrSTVoBEzAXYKZMM2m4=,R4QeD2psvrTr8tkBTjnnfUBw+YR4di+GToGjWYeR7qZk9hldUVLlZUsEEPWjtBpz+UURVmplIn5WM9Ge29ft5aS4oKDdPlIH8kWNIs9Y3r9TgH3MnSUTGrgayaNniY9Ji5wNZiZ9cE2CFzlxoyuZxOcSVfOxUw70ty0ukLVM/78=";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/demo2/sayHello');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

  Return result:

ƒ (e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}
VM156:8 hello world --- 2

Description Cross-Domain success!

  • Another test to see if the domain is still valid cross-domain, in https://www.baidu.com test as above it, return the result:
OPTIONS http://127.0.0.1:8080/demo2/sayHello 403
(anonymous)
Access to XMLHttpRequest at 'http://127.0.0.1:8080/demo2/sayHello' 
from origin 'http://www.cnblogs.com' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

     Description Cross-domain failure! The program proved successful cross-domain can specify a part of domain name!

  2.2.2 Option Two: CORS Global Configuration - to achieveWebMvcConfigurer

  • New cross-domain configuration class: CorsConfig.java:
 1 /**
 2  * 跨域配置
 3  */
 4 @Configuration
 5 public class CorsConfig implements WebMvcConfigurer {
 6 
 7     @Bean
 8     public WebMvcConfigurer corsConfigurer()
 9     {
10         return new WebMvcConfigurer() {
11             @Override
12             public void addCorsMappings(CorsRegistry registry) {
13                 registry.addMapping("/**").
14                         allowedOrigins ( "https://www.dustyblog.cn"). // permit cross-domain, you can use any domain name * Permits the use of 
15                          allowedMethods ( "*"). // allows any method (post, get, etc.) 
16                          allowedHeaders ( "*"). // allows any request header 
. 17                          allowCredentials ( to true ). // tape cookie information 
18 is                          exposedHeaders (HttpHeaders.SET_COOKIE) .maxAge (3600L); // the maxAge (3600) showed that in 3600 seconds , do not need to send pre-check request, the result may cache 
19              }
 20          };
 21      }
 22 }
  • Test, allowing access to the domain name of https://www.dustyblog.cn/ console input (note that this request is http://127.0.0.1:8080/demo3):
var token= "LtSFVqKxvpS1nPARxS2lpUs2Q2IpGstidMrS8zMhNV3rT7RKnhLN6d2FFirkVEzVIeexgEHgI/PtnynGqjZlyGkJa4+zYIXxtDMoK/N+AB6wtsskYXereH3AR8kWErwIRvx+UOFveH3dgmdw1347SYjbL/ilGKX5xkoZCbfb1f0=,LZkg22zbNsUoHAgAUapeBn541X5OHUK7rLVNHsHWDM/BA4DCIP1f/3Bnu4GAElQU6cds/0fg9Li5cSPHe8pyhr1Ii/TNcUYxqHMf9bHyD6ugwOFTfvlmtp6RDopVrpG24RSjJbWy2kUOOjjk5uv6FUTmbrSTVoBEzAXYKZMM2m4=,R4QeD2psvrTr8tkBTjnnfUBw+YR4di+GToGjWYeR7qZk9hldUVLlZUsEEPWjtBpz+UURVmplIn5WM9Ge29ft5aS4oKDdPlIH8kWNIs9Y3r9TgH3MnSUTGrgayaNniY9Ji5wNZiZ9cE2CFzlxoyuZxOcSVfOxUw70ty0ukLVM/78=";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8080/demo3/sayHello');
xhr.setRequestHeader("x-access-token",token);
xhr.send(null);
xhr.onload = function(e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}

  Return result:

ƒ (e) {
    var xhr = e.target;
    console.log(xhr.responseText);
}
VM433:8 hello world --- 3

 Explain the success of cross-domain, such as another URL https://www.baidu.com tests still need cross-domain error occurs, to prove that the configuration is correct, the program test.

  2.2.3 Option Three: Interceptor Filter to achieve

  By implementing Fiterthe interface in the request to add some Headerproblems to solve cross-domain

 1 @Component
 2 public class CorsFilter implements Filter {
 3 
 4     @Override
 5     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 6             throws IOException, ServletException {
 7         HttpServletResponse res = (HttpServletResponse) response;
 8         res.addHeader("Access-Control-Allow-Credentials", "true");
 9         res.addHeader("Access-Control-Allow-Origin", "*");
10         res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
11         res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
12         if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
13             response.getWriter().println("ok");
14             return;
15         }
16         chain.doFilter(request, response);
17     }
18     @Override
19     public void destroy() {
20     }
21     @Override
22     public void init(FilterConfig filterConfig) throws ServletException {
23     }
24 }

 So far, cross-domain request is complete, there are more and better method friends welcome message!

 Good text around to learn from: https://www.cnblogs.com/vandusty/p/11408422.html

Guess you like

Origin www.cnblogs.com/zhaosq/p/11410682.html