Home >Java >javaTutorial >How does springboot solve cross-domain problems?

How does springboot solve cross-domain problems?

不言
不言forward
2019-03-19 10:17:386067browse

The content of this article is about how springboot solves cross-domain problems? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a cross-domain HTTP request?

For security reasons, modern browsers must comply with the same origin policy when using the XMLHttpRequest object to initiate HTTP requests, otherwise Cross-domain HTTP requests are prohibited by default. Cross-domain HTTP requests refer to resources in domain A requesting resources in domain B. For example, the js code deployed on Nginx on machine A requests the RESTful interface deployed on Tomcat on machine B through ajax. (Recommended: Java Video Tutorial)

Different IP (domain name) or different ports will cause cross-domain problems. In order to solve cross-domain problems, there have been solutions such as jsonp and proxy files. The application scenarios were limited and the maintenance costs were high. Until HTML5 brought the CORS protocol.

CORS is a W3C standard, the full name is "Cross-origin resource sharing" (Cross-origin resource sharing), which allows browsers to issue XMLHttpRequest requests to cross-origin servers, thereby overcoming the problem that AJAX can only be used from the same origin. limit. It adds a special Header [Access-Control-Allow-Origin] to the server to tell the client about cross-domain restrictions. If the browser supports CORS and determines that the Origin is passed, XMLHttpRequest will be allowed to initiate cross-domain requests.

CROS common header

Access-Control-Allow-Origin: http://somehost.com indicates that http://somehost.com is allowed to initiate cross-domain requests.
Access-Control-Max-Age:86400 means that there is no need to send pre-verification requests within 86400 seconds.
Access-Control-Allow-Methods: GET, POST, PUT, DELETE indicates methods that allow cross-domain requests.
Access-Control-Allow-Headers: content-type indicates that cross-domain requests are allowed to include content-type

2. CORS implements cross-domain access

Authorization method
Method 1: Return a new CorsFilter
Method 2: Override WebMvcConfigurer
Method 3: Use annotation (@CrossOrigin)
Method 4: Manually set the response header (HttpServletResponse)

Note: Methods 1 and 2 belong to the global CORS configuration, and methods 3 and 4 belong to the local CORS configuration. If local cross-domain is used, it will override the global cross-domain rules, so the @CrossOrigin annotation can be used for finer-grained cross-domain resource control.

1. Return the new CorsFilter (global cross-domain)

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
          //放行哪些原始域
          config.addAllowedOrigin("*");
          //是否发送Cookie信息
          config.setAllowCredentials(true);
          //放行哪些原始域(请求方式)
          config.addAllowedMethod("*");
          //放行哪些原始域(头部信息)
          config.addAllowedHeader("*");
          //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
          config.addExposedHeader("*");

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

2. Override WebMvcConfigurer (global cross-domain)

Any configuration class, Return a new WebMvcConfigurer Bean and rewrite the cross-domain request processing interface it provides to add mapping paths and specific CORS configuration information.

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET","POST", "PUT", "DELETE")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }
}

3. Use annotations (local cross-domain)

Use the annotation @CrossOrigin on the method (@RequestMapping):

@RequestMapping("/hello")
@ResponseBody
@CrossOrigin("http://localhost:8080") 
public String index( ){
    return "Hello World";
}

or on the controller (@Controller) Use the annotation @CrossOrigin:

@Controller
@CrossOrigin(origins = "http://xx-domain.com", maxAge = 3600)
public class AccountController {

    @RequestMapping("/hello")
    @ResponseBody
    public String index( ){
        return "Hello World";
    }
}
  1. Manually set the response header (partial cross-domain)

Use the HttpServletResponse object to add the response header (Access-Control-Allow-Origin) for authorization Original domain, the value of Origin here can also be set to "*", which means all are allowed.

@RequestMapping("/hello")
@ResponseBody
public String index(HttpServletResponse response){
    response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
    return "Hello World";
}

3. Test cross-domain access

First use Spring Initializr to quickly build a Maven project without changing anything. In the static directory, add a page: index.html to simulate cross-domain access. Target address: http://localhost:8090/hello

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Page Index</title>
</head>
<body>
<h2>前台系统</h2>
<p id="info"></p>
</body>
<script src="webjars/jquery/3.2.1/jquery.js"></script>
<script>
    $.ajax({
        url: 'http://localhost:8090/hello',
        type: "POST",
        xhrFields: {
           withCredentials: true //允许跨域认证
        },
        success: function (data) {
            $("#info").html("跨域访问成功:"+data);
        },
        error: function (data) {
            $("#info").html("跨域失败!!");
        }
    })
</script>
</html>

Then create another project, add the Config directory in the Root Package and create a configuration class to enable global CORS.

package com.hehe.yyweb.config;

@Configuration
public class GlobalCorsConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

Next, simply write a Rest interface and specify the application port as 8090.

package com.hehe.yyweb;

@SpringBootApplication
@RestController
public class YyWebApplication {

    @Bean
    public TomcatServletWebServerFactory tomcat() {
        TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory();
        tomcatFactory.setPort(8090); //默认启动8090端口
        return tomcatFactory;
    }

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

    public static void main(String[] args) {
        SpringApplication.run(YyWebApplication.class, args);
    }
}

Finally, start the two applications respectively, and then access: http://localhost:8080/index.html in the browser. JSON data can be received normally, indicating that the cross-domain access is successful! !


The above is the detailed content of How does springboot solve cross-domain problems?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete