Three methods of springboot configuration to solve cross-domain problems

Three methods of springboot configuration to solve cross-domain problems

First, implement the WebMvcConfigurer class

Code directly:

@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer{

	@Override
	public void addCorsMappings(CorsRegistry registry) {
	    // 设置允许跨域的路径
	    registry.addMapping("/**")
	        // 设置允许跨域请求的域名
	        .allowedOrigins("*")
	        // 是否允许证书 不再默认开启
	        .allowCredentials(true)
	        // 设置允许的方法
	        .allowedMethods("*")
	        // 跨域允许时间
	        .maxAge(3600);
	}
}

This configuration is fine for springboot, and it is configured in zuul in springcloud. However,
there is a problem. When the server throws 500, there is still a cross-domain problem.
This is the simplest.

2. Write configuration class (recommended)
@Configuration
public class CorsConfig {
	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		//corsConfiguration.addAllowedOrigin("http://10.38.4.181:8020/"); // 允许任何域名使用
		corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
		corsConfiguration.addAllowedHeader("*"); // 允许任何头
		corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
		corsConfiguration.setAllowCredentials(true);

		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
		return new CorsFilter(source);
	}
}
3. Configure the request header in the filter
/**
 * 处理跨域问题
 *
 */

@Component
public class OriginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    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,PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }
}

This method is like the configuration class of the anti-SQL injection method. For details, please refer to the blog of anti-SQL injection and XSS attack.

Published 67 original articles · Liked12 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/m0_37635053/article/details/103566221