• 解决SpringBoot跨域的三种方式


    原文链接: https://3water.com/article/cMTM39MjMzdLmY5

    一、什么是跨域

    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(全局跨域)

    复制
    1. import org.springframework.boot.SpringBootConfiguration;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.web.cors.CorsConfiguration;
    4. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    5. import org.springframework.web.filter.CorsFilter;
    6. @SpringBootConfiguration
    7. public class WebGlobalConfig {
    8. @Bean
    9. public CorsFilter corsFilter() {
    10. //创建CorsConfiguration对象后添加配置
    11. CorsConfiguration config = new CorsConfiguration();
    12. //设置放行哪些原始域
    13. config.addAllowedOrigin("*");
    14. //放行哪些原始请求头部信息
    15. config.addAllowedHeader("*");
    16. //暴露哪些头部信息
    17. config.addExposedHeader("*");
    18. //放行哪些请求方式
    19. config.addAllowedMethod("GET"); //get
    20. config.addAllowedMethod("PUT"); //put
    21. config.addAllowedMethod("POST"); //post
    22. config.addAllowedMethod("DELETE"); //delete
    23. //corsConfig.addAllowedMethod("*"); //放行全部请求
    24. //是否发送Cookie
    25. config.setAllowCredentials(true);
    26. //2. 添加映射路径
    27. UrlBasedCorsConfigurationSource corsConfigurationSource =
    28. new UrlBasedCorsConfigurationSource();
    29. corsConfigurationSource.registerCorsConfiguration("/**", config);
    30. //返回CorsFilter
    31. return new CorsFilter(corsConfigurationSource);
    32. }
    33. }

    如果你使用的是高版本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(全局跨域)

    复制
    1. import org.springframework.boot.SpringBootConfiguration;
    2. import org.springframework.web.servlet.config.annotation.CorsRegistry;
    3. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    4. @SpringBootConfiguration
    5. public class CorsConfig implements WebMvcConfigurer {
    6. @Override
    7. public void addCorsMappings(CorsRegistry registry) {
    8. //添加映射路径
    9. registry.addMapping("/**")
    10. //是否发送Cookie
    11. .allowCredentials(true)
    12. //设置放行哪些原始域 SpringBoot2.4.4下低版本使用.allowedOrigins("*")
    13. .allowedOriginPatterns("*")
    14. //放行哪些请求方式
    15. .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
    16. //.allowedMethods("*") //或者放行全部
    17. //放行哪些原始请求头部信息
    18. .allowedHeaders("*")
    19. //暴露哪些原始请求头部信息
    20. .exposedHeaders("*");
    21. }
    22. }

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

    复制
    1. @Target({ElementType.TYPE, ElementType.METHOD})
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface CrossOrigin {
    5. //这origins和value是一样的
    6. //允许来源域名的列表,例如 'www.jd.com',匹配的域名是跨域预请求 Response 头中的'Access-Control-Aloow_origin'
    7. //字段值。不设置确切值时默认支持所有域名跨域访问。
    8. @AliasFor("origins")
    9. String[] value() default {};
    10. @AliasFor("value")
    11. String[] origins() default {};
    12. //高版本下Spring2.4.4使用originPatterns 而不是value 和 origins
    13. String[] originPatterns() default {};
    14. //跨域请求中允许的请求头中的字段类型, 该值对应跨域预请求 Response 头中的 'Access-Control-Allow-Headers' 字段值。
    15. //不设置确切值默认支持所有的header字段(Cache-Controller、Content-Language、Content-Type、
    16. //Expires、Last-Modified、Pragma)跨域访问
    17. String[] allowedHeaders() default {};
    18. //跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、
    19. //Pragma这六个基本字段之外的其他字段信息,对应的是跨域请求 Response 头中的 'Access-control-Expose-Headers'字段值
    20. String[] exposedHeaders() default {};
    21. //跨域HTTP请求中支持的HTTP请求类型(GET、POST...),不指定确切值时默认与 Controller 方法中的 methods 字段保持一致。
    22. RequestMethod[] methods() default {};
    23. //该值对应的是是跨域请求 Response 头中的 'Access-Control-Allow-Credentials' 字段值。
    24. //浏览器是否将本域名下的 cookie 信息携带至跨域服务器中。默认携带至跨域服务器中,但要实现 cookie
    25. //共享还需要前端在 AJAX 请求中打开 withCredentials 属性。
    26. String allowCredentials() default "";
    27. //该值对应的是是跨域请求 Response 头中的 'Access-Control-Max-Age' 字段值,表示预检请求响应的缓存持续的最大时间,
    28. //目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求
    29. long maxAge() default -1;
    30. }

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

    复制
    1. @Controller
    2. @RequestMapping("/shop")
    3. @CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
    4. public class ShopController {
    5. @GetMapping("/")
    6. @ResponseBody
    7. public Map<String, Object> findAll() {
    8. //返回数据
    9. return DataSchool.getStudents();
    10. }
    11. }

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

    复制
    1. @Controller
    2. @RequestMapping("/shop")
    3. public class ShopController {
    4. @GetMapping("/")
    5. @ResponseBody
    6. //更小的解决跨域 设置只能某些地址访问
    7. @CrossOrigin(originPatterns = "http://localhost:8080")
    8. public Map<String, Object> findAll() {
    9. //返回数据
    10. return DataSchool.getStudents();
    11. }
    12. }

    以上就是解决SpringBoot跨域的三种方式的详细内容,更多关于SpringBoot跨域的资料请关注三水点靠木其它相关文章!

  • 相关阅读:
    无废话XML--XML约束(DTD)
    无废话XML--XML细节
    XML,HTML,XHTML
    javabean内省
    反射应用--IOC和AOP
    JDK动态代理
    反射
    类加载机制
    linkin大话数据结构--泛型
    java异常处理
  • 原文地址:https://www.cnblogs.com/fswhq/p/16189162.html
Copyright © 2020-2023  润新知