[SpringBoot] Solve cross-domain problems

Springboot version:

2.7.8

cross-domain issues

Due to the browser's same-origin policy restrictions. The same origin policy (Same origin policy) is a convention, which 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. It can be said that the Web is built on the basis of the same-origin policy, and the browser is only an implementation of the same-origin policy.

The same-origin policy prevents javascript scripts from one domain from interacting with content from another domain. The so-called same origin (that is, in the same domain) means that two pages have the same protocol (protocol), host (host) and port number (port)

How is it cross-domain?

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

solution

Add a configuration class

 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    
    

    private CorsConfiguration buildConfig() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许任何域名使用
        corsConfiguration.addAllowedOriginPattern("*");
        // 允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 允许任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

	//下面两个方法二选一
    @Bean
    public CorsFilter corsFilter() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
    
    // 下面代码是将一个名为corsFilter的CorsFilter过滤器注册到Servlet容器中。具体来说,setOrder(-101)方法设置了该过滤器的执行顺序为最低优先级。当请求到达Web应用程序时,CorsFilter过滤器将首先被执行,以检查是否需要进行跨域请求的CORS处理。如果需要进行跨域请求的CORS处理,则CorsFilter过滤器将允许请求通过,否则将拒绝请求并返回错误响应。 
	@Bean
    public FilterRegistrationBean corsFilterBean() {
    
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 对接口配置跨域设置
        source.registerCorsConfiguration("/**", buildConfig());
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<CorsFilter> filterRegistrationBean = new FilterRegistrationBean<>(corsFilter);
        filterRegistrationBean.setOrder(-101);
        return filterRegistrationBean;
    }

}

Guess you like

Origin blog.csdn.net/daohangtaiqian/article/details/130205261