Home > Java > javaTutorial > What are the ways Spring Boot implements cross-domain implementation?

What are the ways Spring Boot implements cross-domain implementation?

WBOY
Release: 2023-05-18 10:10:26
forward
1398 people have browsed it

1. Why cross-domain problems occur

It is due to the same-origin policy restrictions of the browser. Same origin policy (Same origin policy) is a convention. It is the core and most basic security function of the browser. If the same origin policy is missing, the normal functions of the browser may be affected. The Web is built based on the same-origin policy, and the browser is just a way to implement the same-origin policy.

In JavaScript, the same-origin policy will limit interactions between different domains and prevent cross-domain attacks. The so-called same origin (that is, in the same domain) means that the two pages have the same protocol, host and port

2. What is cross-domain

When any one of the protocol, domain name, and port of a request URL is different from the current page URL, it is cross-domain

What are the ways Spring Boot implements cross-domain implementation?

3. Non-original origin restriction

  1. Unable to read Cookie, LocalStorage and IndexedDB of non-homogeneous web pages

  2. Unable to access the DOM of non-homologous web pages

  3. Unable to send AJAX requests to non-original addresses

4. How the java backend implements CORS cross-domain requests

For CORS cross-domain requests, There are mainly the following methods to choose from:

  1. Return new CorsFilter

  2. Rewrite WebMvcConfigurer

  3. Use the annotation @CrossOrigin

  4. Manually set the response header (HttpServletResponse)

  5. ##Customize web filter to achieve cross-domain

Note:

  • CorFilter / WebMvConfigurer / @CrossOrigin requires SpringMVC version 4.2 or above to support, corresponding to springBoot version 1.3 or above

  • The first two methods are global CORS configuration, while the latter two are 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.

  • In fact, no matter which solution, the ultimate goal is to modify the response header, add the data required by the browser to the response header, and then achieve cross-domain

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

In any configuration class, return a new CorsFIlter Bean and add the mapping path and specific CORS configuration path.

@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 corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }
}
Copy after login

2. Override WebMvcConfigurer (global cross-domain)

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOrigins("*")
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
Copy after login

3. Use annotations (local cross-domain)

Use annotations@ on the controller (class) CrossOrigin:, indicating that all methods of this class allow cross-domain.

@RestController
@CrossOrigin(origins = "*")
public class HelloController {
    @RequestMapping("/hello")
    public String hello() {
        return "hello world";
    }
}
Copy after login

Use the annotation @CrossOrigin on the method:

@RequestMapping("/hello")
    @CrossOrigin(origins = "*")
     //@CrossOrigin(value = "http://localhost:8081") //指定具体ip允许跨域
    public String hello() {
        return "hello world";
    }
Copy after login

4. Manually set the response header (local cross-domain)

Use the HttpServletResponse object to add the response header (Access-Control- Allow-Origin) to authorize the original domain. The value of Origin here can also be set to "*", indicating that all permissions are allowed.

@RequestMapping("/index")
public String index(HttpServletResponse response) {
    response.addHeader("Access-Allow-Control-Origin","*");
    return "index";
}
Copy after login

5. Use custom filter to achieve cross-domain

First write a filter, which can be named MyCorsFilter.java

package com.mesnac.aop;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyCorsFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}
Copy after login

Configure this filter in web.xml device to make it effective

<!-- 跨域访问 START-->
<filter>
 <filter-name>CorsFilter</filter-name>
 <filter-class>com.mesnac.aop.MyCorsFilter</filter-class>
</filter>
<filter-mapping>
 <filter-name>CorsFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 跨域访问 END  -->
Copy after login

The above is the detailed content of What are the ways Spring Boot implements cross-domain implementation?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template