SpringBoot解决跨域问题

分手后的思念是犯贱 2022-03-22 08:44 450阅读 0赞

前言

跨域问题,是web开发都绕不开的难题。但我们首先要明确以下几点

  1. 跨域只存在于浏览器端,不存在于安卓/ios/Node.js/python/ java等其它环境
  2. 跨域请求能发出去,服务端能收到请求并正常返回结果,只是结果被浏览器拦截了。

之所以会跨域,是因为受到了同源策略的限制,同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。

浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求,默认情况下是被禁止的。换句话说,浏览器安全的基石是同源策略。

同源策略限制了从同一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。

更多关于跨域请求的解释,参考 1、什么是跨域请求?

什么是CROS?

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。它通过服务器增加一个特殊的Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持CORS、并且判断Origin通过的话,就会允许XMLHttpRequest发起跨域请求。

CORS Header

  • Access-Control-Allow-Origin: http://www.xxx.com
  • Access-Control-Max-Age:86400
  • Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
  • Access-Control-Allow-Headers: content-type
  • Access-Control-Allow-Credentials: true

含义解释:
1、Access-Control-Allow-Origin 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
2、Access-Control-Max-Age 设置在86400秒不需要再发送预校验请求
3、Access-Control-Allow-Methods 设置允许跨域请求的方法
4、Access-Control-Allow-Headers 允许跨域请求包含content-type
5、Access-Control-Allow-Credentials 设置允许Cookie

filter方式解决跨域

在项目中添加filter类:

  1. /**
  2. * @Description 用于解决跨域问题
  3. * @Author chenlinghong
  4. * @Date 2018/12/1 16:20
  5. **/
  6. public class AllowOriginFilter implements Filter {
  7. @Override
  8. public void init(FilterConfig filterConfig) throws ServletException {
  9. // TODO 其他处理
  10. }
  11. @Override
  12. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  13. HttpServletResponse response = (HttpServletResponse) servletResponse;
  14. HttpServletRequest request = (HttpServletRequest) servletRequest;
  15. String origin = request.getHeader("Origin");
  16. if (StringUtils.isNotBlank(origin)) {
  17. //设置响应头,允许跨域访问
  18. //带cookie请求时,必须为全匹配,不能使用*
  19. /**
  20. * 表示允许 origin 发起跨域请求。
  21. */
  22. response.addHeader("Access-Control-Allow-Origin", origin);
  23. }
  24. /**
  25. * GET,POST,OPTIONS,PUT,DELETE 表示允许跨域请求的方法
  26. */
  27. response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
  28. /**
  29. * 表示在86400秒内不需要再发送预校验请求
  30. */
  31. response.addHeader("Access-Control-Max-Age", "86400");
  32. //支持所有自定义头
  33. String headers = request.getHeader("Access-Control-Request-Headers");
  34. if (StringUtils.isNotBlank(headers)) {
  35. //允许JSON请求,并进行预检命令缓存
  36. response.addHeader("Access-Control-Allow-Headers", headers);
  37. }
  38. response.addHeader("Access-Control-Max-Age", "3600");
  39. //允许cookie
  40. response.addHeader("Access-Control-Allow-Credentials", "true");
  41. filterChain.doFilter(servletRequest, response);
  42. }
  43. @Override
  44. public void destroy() {
  45. // TODO 其他处理
  46. }
  47. }

SpringBoot项目解决跨域

在SpringBoot项目中,推崇的都是约定优于配置,尽量少的配置。以下提供两种方式,选其一即可

1、注入重写方法的WebMvcConfigurer

在解决跨域问题上,我们只需要进行注入一个对象,我们对其进行重写其方法即可。

注:整个Application的handler均允许跨域。

CORSConfig.java

  1. /**
  2. * @Description 跨域配置
  3. * @Author chenlinghong
  4. * @Date 2019/1/27 13:31
  5. **/
  6. @Configuration
  7. public class CORSConfig {
  8. @Bean
  9. public WebMvcConfigurer corsConfigurer(){
  10. return new WebMvcConfigurer() {
  11. @Override
  12. public void addCorsMappings(CorsRegistry registry) {
  13. registry.addMapping("/**")
  14. .allowedHeaders("*")
  15. .allowedMethods("*")
  16. .allowedOrigins("*");
  17. }
  18. };
  19. }
  20. }

2、@CrossOrigin - 终极Boss

只需要在允许跨域的接口方法上进行添加注解即可,也可以直接在Controller类上添加,表示该Controller所有方法均允许跨域访问。

You can add to your @RequestMapping annotated handler method a @CrossOrigin annotation in order to enable CORS on it (by default @CrossOrigin allows all origins and the HTTP methods specified in the @RequestMapping annotation):

  1. @RestController
  2. @RequestMapping("/account")
  3. public class AccountController {
  4. @CrossOrigin
  5. @GetMapping("/{id}")
  6. public Account retrieve(@PathVariable Long id) {
  7. // ...
  8. }
  9. @DeleteMapping("/{id}")
  10. public void remove(@PathVariable Long id) {
  11. // ...
  12. }
  13. }

It is also possible to enable CORS for the whole controller:

  1. @CrossOrigin(origins = "http://domain2.com", maxAge = 3600)
  2. @RestController
  3. @RequestMapping("/account")
  4. public class AccountController {
  5. @GetMapping("/{id}")
  6. public Account retrieve(@PathVariable Long id) {
  7. // ...
  8. }
  9. @DeleteMapping("/{id}")
  10. public void remove(@PathVariable Long id) {
  11. // ...
  12. }
  13. }

以上代码引用自:6、CORS support in Spring Framework

参考链接

1、什么是跨域请求?
2、同源策略 - 百度百科
3、Spring Boot设置跨域访问
4、Cross-origin resource sharing - wikipedia
5、我知道的跨域与安全
6、CORS support in Spring Framework
7、CORS跨域 GET、POST、PUT、DELETE等请求

发表评论

表情:
评论列表 (有 0 条评论,450人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Springboot解决问题

    (跨域资源共享)策略,允许跨域请求。常见的解决方法是在后端代码中添加CORS配置,允许特定的域名或所有域名的请求。可以使用Spring Boot提供的@CrossOrig...

    相关 springboot解决问题

        跨域是前后端分离,前端页面发起异步ajax请求,而浏览器因为同源策略导致请求失败,请求正确到了服务端,而且服务端也正常处理,只不过浏览器不认可,所以跨域问题的门槛是浏览