13:SpringBoot跨域解决方案-Java Spring

142 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

13.1 CorsFilter

SpringBoot设置CORS的的本质都是通过设置响应头信息来告诉前端该请求是否支持跨域

CorsFilter是一种通用解决方案,用于将跨域资源共享 (CORS) 支持适配到 Java Web 应用程序。

过滤器CorsFilter为第三方组件,可以插入到任何标准的 Java Servlet 容器中,以处理对驻留在服务器上的Servlet、JSP 和 HTML 文件的跨站点请求

参考:CORS Filter

依赖引入

<dependency>
	<groupId>com.thetransactioncompany</groupId>
	<artifactId>cors-filter</artifactId>
	<version>[ version ]</version>
</dependency>

配置类

提供一个自定义的 @Configuration 配置类,自定义 CorsFilter 过滤器,添加映射路径和具体的 CORS 配置路径

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 CorsFilterConfiguration {
 
    @Bean
    public CorsFilter corsFilter() {
        //1.添加CORS配置信息
        CorsConfiguration configuration = new CorsConfiguration();
        
        //允许所有源请求跨域,* 表示不限制
        configuration.addAllowedOrigin("*");
        
		//跨域请求默认不包含Cookie,设置为true可以包含Cookie
        configuration.setAllowCredentials(true);
        
        //允许所有方法跨域,或者设置请求方式GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
        configuration.addAllowedMethod("*");
        
        //允许所有原始请求头信息
        configuration.addAllowedHeader("*");
        
  		//允许暴露哪些头信息,为了安全问题不能设置成*,否则会报错:throw new IllegalArgumentException("'*' is not a valid exposed header value");
  	    configuration.addExposedHeader("");
  	    
        //设置请求有效时间
        configuration.setMaxAge(3600L);
        
        //2.添加映射路径,即允许对方可以访问本应用下的哪些请求接口,/** 表示所有请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);
        
        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

13.2 @CrossOrigin

@CrossOrigin注解表示局部跨域,可以用在类或者方法上

SpringMVC在4.2以上版本才支持@CrossOrigin

maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/account")

public class TestController {
	//origins表示允许的域,用在控制器方法上,表示该方法都允许跨域
    @CrossOrigin(origins = "*")
    @GetMapping("test")
    public String test() {
        return "success";
    }
}
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
//maxAge表示准备响应前的缓存持续的最大时间,单位为秒,用在控制器类上,表示该类的所有方法都允许跨域
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")

public class TestController {
    @GetMapping("test")
    public String test() {
        return "success";
    }
}

13.3 WebMvcConfigurer

实现 WebMvcConfigurer全局跨域),重写 addCorsMappings 方法设置跨域映射

addMapping 配置可以被跨域的路径,可以任意配置,可以具体到直接请求路径。

allowedMethods:允许所有的请求方法访问该跨域资源服务器,如:POST、GET、PUT、DELETE等。 allowedOrigins:允许所有的请求域名访问我们的跨域资源,可以固定单条或者多条内容,

如:“www.aaa.com”,只有该域名可以访问我们的跨域资源。 allowedHeaders:允许所有的请求header访问,可以自定义设置任意请求头信息。

@Configuration
public class CorsConfig implements WebMvcConfigurer {
	@Override
	public void addCorsMappings(CorsRegistry registry) {

		registry.addMapping("/**")
		//允许所有源请求跨域,* 表示不限制
		.allowedOrigins("*")
        //允许所有原始请求头信息
		.allowedHeaders("*")
		//允许所有方法跨域,或者设置请求方式GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
		.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD")
		//允许包含Cookie
		.allowCredentials(true)
  		//允许暴露哪些头信息,为了安全问题不能设置成*
		//.exposedHeaders();
		.maxAge(3600);
	}
}