美文网首页
SpringBoot解决跨域的三种方式

SpringBoot解决跨域的三种方式

作者: 山巅自相见 | 来源:发表于2021-09-08 11:03 被阅读0次

什么是跨域

为什么会出现跨域问题

处于浏览器的同源的策略限制。同源策略(Sameoriginpolicy)是一种约定,他是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建子啊同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策列会阻止一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)
简单地说A应用只能访问A应用后台传来的数据,B应用只能范根B应用后台传来的数据。如果A应用用Ajax获取数据时的URL地址中协议、端口、域名其中有一个和B对应的话,则是A应用跨域了想获取B的数据,是不允许的

什么是跨域

当一个请求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)

非同源限制

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

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

如何解决跨域问题

服务端使用纯代码的方式逻辑解决跨域问题,如果使用Spring Boot的话请看下章
【腾讯文档】JSONP跨域解决https://docs.qq.com/doc/DVEVTemdrcVVjSFlE

spring boot解决跨域问题

五种解决方式:
1. 返回新的CorsFilter
2. 重写WebMvcConfigurer
3. 使用注解@CrossOrigin
4. 手动设置响应头(HttpServletResponse)
注意:
CorsFilter/WebMvcConfigurer/@CrossOrigin需要SpringMVC4.2以上的版本才支持,对应SpringBoot1.3以上版本才支持
前两种方式属于全局Cors配置,后两种属于局部Cors配置。如果使用了局部跨域是会覆盖全局跨域的规则,所以可以通过@CrossOrigin来进行细粒度更高的跨域资源控制。
其实无论哪种方式,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域

1.配置CorsFilter(全局跨域)

import lombok.extern.slf4j.Slf4j;
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
  * 跨域前后端配置类
  * 赵毅梵
  * 2021/9/8
  **/
@Configuration
@Slf4j
public class CorsConfig {
  @Bean
  public CorsFilter corsFilter() {
    // 1.添加CORS配置信息
    CorsConfiguration config = new CorsConfiguration();
    // 放行哪些原始域
    config.addAllowedOrigin("*");
    // 是否发送Cookie信息
    config.setAllowCredentials(true);
    // 放行哪些原始域(请求方式)
    config.addAllowedMethod("*");
    // 放行哪些原始域(头部信息)
    config.addAllowedHeader("*");
    // 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
    // config.addExposedHeader("*");
    config.addExposedHeader("Content-Type");
    config.addExposedHeader( "X-Requested-With");
    config.addExposedHeader("accept");
    config.addExposedHeader("Origin");
    config.addExposedHeader( "Access-Control-Request-Method");
    config.addExposedHeader("Access-Control-Request-Headers");
    // 2.添加映射路径
    UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
    configSource.registerCorsConfiguration("/**", config);
    // 3.返回新的CorsFilter.
    return new CorsFilter(configSource);
  }
}

如果使用的是高版本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时,AllowedOriginates不能包含特殊值“
”,因为不能在“Access Control Allow Originary”响应头上设置该值。要允许凭据到一组原点,请显式列出它们,或者考虑使用“Apple Debug模式”。
解决:把config.addAllowedOrigin("");替换成config.addAllowedOriginPattern("");**

2. 重写WebMvcConfigurer(全局跨域)

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

/**
  * 跨域前后端配置类
  * 赵毅梵
  * 2021/9/8
  **/
@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("*");
  }
}

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;
}

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();
  }
}

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

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

相关文章

网友评论

      本文标题:SpringBoot解决跨域的三种方式

      本文链接:https://www.haomeiwen.com/subject/kbtvwltx.html