软件编程
位置:首页>> 软件编程>> java编程>> 解决SpringBoot跨域的三种方式

解决SpringBoot跨域的三种方式

作者:蚂蚁小哥  发布时间:2021-06-20 13:20:08 

标签:SpringBoot,跨域

一、什么是跨域

1.1、为什么会出现跨域问题

出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

简单说A应用只能访问A应用后台传来数据,B应用只能访问B应用后台传来的数据,如果A应用用Ajax获取数据时的URL地址中的协议、端口、域名其中有一个和B应用对应的话,则是A应用跨域了想获取B应用数据,是不允许的

1.2、什么是跨域

当一个请求url的 协议、域名、端口 三者之间任意一个与当前页面url不同即为跨域

当前页面URL被请求页面URL是否跨域原因
http://www.test.com/http://www.test.com/index.html同源(协议、域名、端口号相同)
http://www.test.com/https://www.test.com/index.html跨域协议不同(http/https)
http://www.test.com/http://www.baidu.com/跨域主域名不同(test/baidu)
http://www.test.com/http://blog.test.com/跨域子域名不同(www/blog)
http://www.test.com:8080/http://www.test.com:7001/跨域端口号不同(8080/7001)

1.3、非同源限制

浏览器为了安全性,限制了一些请求无法访问非同源URL

【1】无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB
【2】无法接触非同源网页的 DOM
【3】无法向非同源地址发送 AJAX 请求

1.4、如何解决跨域问题

服务端使用纯代码的方式逻辑解决跨域问题,如果使用SpringBoot的话请看下章

【腾讯文档】JSONP跨域解决 https://docs.qq.com/doc/DVEVTemdrcVVjSFlE

二、SpringBoot解决跨域问题

①:返回新的CorsFilter

②:重写WebMvcConfigurer

③:使用注解@CrossOrigin

注意:CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上上面前两种方式属于全局 CORS 配置,后两种属于局部 CORS配置。如果使用了局部跨域是会覆盖全局跨域的规则,
所以可以通过 @CrossOrigin 注解来进行细粒度更高的跨域资源控制。其实无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域

2.1、配置CorsFilter(全局跨域)


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

@SpringBootConfiguration
public class WebGlobalConfig {

@Bean
   public CorsFilter corsFilter() {

//创建CorsConfiguration对象后添加配置
       CorsConfiguration config = new CorsConfiguration();
       //设置放行哪些原始域
       config.addAllowedOrigin("*");
       //放行哪些原始请求头部信息
       config.addAllowedHeader("*");
       //暴露哪些头部信息
       config.addExposedHeader("*");
       //放行哪些请求方式
       config.addAllowedMethod("GET");     //get
       config.addAllowedMethod("PUT");     //put
       config.addAllowedMethod("POST");    //post
       config.addAllowedMethod("DELETE");  //delete
       //corsConfig.addAllowedMethod("*");     //放行全部请求

//是否发送Cookie
       config.setAllowCredentials(true);

//2. 添加映射路径
       UrlBasedCorsConfigurationSource corsConfigurationSource =
               new UrlBasedCorsConfigurationSource();
       corsConfigurationSource.registerCorsConfiguration("/**", config);
       //返回CorsFilter
       return new CorsFilter(corsConfigurationSource);
   }
}

如果你使用的是高版本SpringBoot2.4.4则需要改动一下,否则后台报错

java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:453) ~[spring-web-5.3.6.jar:5.3.6]

当allowCredentials为true时,alloedOrigins不能包含特殊值“*”,因为该值不能在“Access-Control-Allow-Origin”响应头部中设置。要允许凭据访问一组来源,请显式列出它们或考虑改用“AllowedOriginPatterns”。

解决:把config.addAllowedOrigin("*"); 替换成config.addAllowedOriginPattern("*");

2.2、重写WebMvcConfigurer(全局跨域)


import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootConfiguration
public class CorsConfig implements WebMvcConfigurer {
   @Override
   public void addCorsMappings(CorsRegistry registry) {
       //添加映射路径
       registry.addMapping("/**")
               //是否发送Cookie
               .allowCredentials(true)
               //设置放行哪些原始域   SpringBoot2.4.4下低版本使用.allowedOrigins("*")    
               .allowedOriginPatterns("*")
               //放行哪些请求方式
               .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
               //.allowedMethods("*") //或者放行全部
               //放行哪些原始请求头部信息
               .allowedHeaders("*")
               //暴露哪些原始请求头部信息
               .exposedHeaders("*");
   }
}

2.3、使用注解@CrossOrigin(局部跨域)


@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
   //这origins和value是一样的
   //允许来源域名的列表,例如 'www.jd.com',匹配的域名是跨域预请求 Response 头中的'Access-Control-Aloow_origin'
   //字段值。不设置确切值时默认支持所有域名跨域访问。
   @AliasFor("origins")
   String[] value() default {};
   @AliasFor("value")
   String[] origins() default {};
   //高版本下Spring2.4.4使用originPatterns 而不是value 和 origins
   String[] originPatterns() default {};

//跨域请求中允许的请求头中的字段类型, 该值对应跨域预请求 Response 头中的 'Access-Control-Allow-Headers' 字段值。
   //不设置确切值默认支持所有的header字段(Cache-Controller、Content-Language、Content-Type、
   //Expires、Last-Modified、Pragma)跨域访问
   String[] allowedHeaders() default {};

//跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、
   //Pragma这六个基本字段之外的其他字段信息,对应的是跨域请求 Response 头中的 'Access-control-Expose-Headers'字段值
   String[] exposedHeaders() default {};

//跨域HTTP请求中支持的HTTP请求类型(GET、POST...),不指定确切值时默认与 Controller 方法中的 methods 字段保持一致。
   RequestMethod[] methods() default {};

//该值对应的是是跨域请求 Response 头中的 'Access-Control-Allow-Credentials' 字段值。
   //浏览器是否将本域名下的 cookie 信息携带至跨域服务器中。默认携带至跨域服务器中,但要实现 cookie
   //共享还需要前端在 AJAX 请求中打开 withCredentials 属性。
   String allowCredentials() default "";

//该值对应的是是跨域请求 Response 头中的 'Access-Control-Max-Age' 字段值,表示预检请求响应的缓存持续的最大时间,
   //目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求
   long maxAge() default -1;
}

①:在控制器(类上)使用@CrossOrigin注解,表示该类的所有方法允许跨域


@Controller
@RequestMapping("/shop")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class ShopController {

@GetMapping("/")
   @ResponseBody
   public Map<String, Object> findAll() {
       //返回数据
       return DataSchool.getStudents();
   }
}

②:我们也可以设置更小的粒度,在方法上设置跨域


@Controller
@RequestMapping("/shop")
public class ShopController {

@GetMapping("/")
   @ResponseBody
   //更小的解决跨域 设置只能某些地址访问
   @CrossOrigin(originPatterns = "http://localhost:8080")
   public Map<String, Object> findAll() {
       //返回数据
       return DataSchool.getStudents();
   }
}

来源:https://www.cnblogs.com/antLaddie/p/14751540.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com