跨域资源共享(CORS)是一个安全概念,用于限制浏览器获取资源。防止JS代码,从不同的源头发起请求。
如下例子:Spring Boot的web应用使用的是8080端口,而JS是通过9090端口调用web应用的restful的API。在这样的场景下,就会发现Cross-Origin Resource Sharing的安全隐患。
要处理这种问题,需要进行两步:
①Web服务端应支持Cross-Origin Resource Sharing。
②将这个跨越资源共享设置到Web服务的8080端口上。
在Controller方法上允许CORS
使用在Controller的方法上使用@CrossOrigin注解就可以允许跨域资源共享了。
- @RequestMapping(value = "/products")
- @CrossOrigin(origins = "http://localhost:8080")
-
- public ResponseEntity
- return null;
- }
全局的CORS配置
使用@Bean注解配置CORS。
- @Bean
- public WebMvcConfigurer corsConfigurer() {
- return new WebMvcConfigurerAdapter() {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/products").allowedOrigins("http://localhost:9000");
- }
- };
- }
在Spring Boot加载这个Bean。
- package com.tutorialspoint.demo;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.context.annotation.Bean;
- import org.springframework.web.servlet.config.annotation.CorsRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
- @SpringBootApplication
- public class DemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- @Bean
- public WebMvcConfigurer corsConfigurer() {
- return new WebMvcConfigurerAdapter() {
- @Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/products").allowedOrigins("http://localhost:8080");
- }
- };
- }
- }
这里个人补充下还有一种更简单方法:
- @configuration
- public class CorsConfig implements WebMvcConfigurer{
-
- @Override
- public void addCorsMappings(CorsRegistry registry){
-
- registry.addMaping("/**")
- .allowedOrigins("*")
- .allowCredentails(true)
- .allowedMethods("GET", "POST")
- .maxAge(3600);
- }
- }
其中
addMapping:配置可被跨越的路径;
allowedOrigins:*为所有,所有域都可以来获取资源;
allowCredentials:将请求的响应暴露给页面;
allowedMethods:允许的请求头。