当前位置: 首页 > news >正文

集成sa-token前后端分离部署配置corsFliter解决跨域失效的真正原因

文章目录

  • 1.前言
  • 2.问题复现
  • 3.解决方法
    • 3.1 方式一:后端修改CorsFilter源码
    • 3.2 方式二:前端禁用或移除浏览器referrer-policy引用者策略
  • 4.总结

1.前言

    缘由请参看下面这篇文章:sa-token前后端分离解决跨域的正确姿势

https://mp.weixin.qq.com/s/96WbWL28T5_-xzyCfJ7Stg
https://blog.csdn.net/qq_34905631/article/details/140233780?spm=1001.2014.3001.5501

    这篇文章虽然经过n多次尝试找到了正确的姿势,但是问题的根本原因没有找到,然后我就经过一些思考和探索,我想这个跨域能不能在本地模拟出来,然后起就去找了项目前端人员老王,然后确实模拟出本地跨域,在项目中将之前sa-token前后端分离解决跨域的正确姿势文章中的SimpleCORSFilter注释之后进行了问题复现。

2.问题复现

     spring5.2.15.RELEASE官方mvc的跨域配置如下:

https://docs.spring.io/spring-framework/docs/5.2.15.RELEASE/spring-framework-reference/web.html#mvc-cors-intro

    按照上面链接官方的一种方式,然后新增了一个CustomCorsFilter类如下:

package xxxx.config;import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomCorsFilter extends CorsFilter {public CustomCorsFilter() {super(corsConfigurationSource());}private static CorsConfigurationSource corsConfigurationSource() {CorsConfiguration configuration = new CorsConfiguration();configuration.addAllowedOrigin("*"); // 允许访问的域名,例如 http://localhost:8080configuration.addAllowedHeader("*"); // 允许所有请求头configuration.addAllowedMethod("*"); // 允许所有请求方法configuration.setAllowCredentials(true);UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", configuration);return source;}}

    该CustomCorsFilter的配置写法我搞的一个项目中配置验证过是有效的,但是在最近做的一个项目中使用这个CustomCorsFilter类配置到项目中解决跨域缺没有用,难道是这种配置失效了吗?在上面sa-token前后端分离解决跨域的正确姿势文章中配置了CustomCorsFilter类验证确实是失效了,这个问题真的是让人百思不得其解,当我在项目中重新配置好CustomCorsFilter类之后(SimpleCORSFilter需要注释,因为这个SimpleCORSFilter进过验证时可以行的),紧接着把项目本地跑起来之后,前端模拟跨域请求,我在CorsFilter类的如下代码打上断点:

   @Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);boolean isValid = this.processor.processRequest(corsConfiguration, request, response);//关键就是这里,在这里打上断点if (!isValid || CorsUtils.isPreFlightRequest(request)) {return;}filterChain.doFilter(request, response);}

    CorsUtils.isPreFlightRequest方法上也打上断点:

	public static boolean isPreFlightRequest(HttpServletRequest request) {return (HttpMethod.OPTIONS.matches(request.getMethod()) &&request.getHeader(HttpHeaders.ORIGIN) != null &&request.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) != null);}

    然后断点截图如下:

    登录接口是一个http加域名的复杂跨域请求会发送一个预检测请求(OPTIONS请求)

cors调试图片2

    在集成了sa-token的项目中OncePerRequestFilter的doFilterInternal方法打上断点,发现有如下过滤器:

cors调试图片2

    可以看到上面我们自定一的CustomCorsFilter是在最先执行的,sa-token相关的两个filter:saPathCheckFilterForServlet和SaServletFilter都是后面才执行的,所以之前的其他猜想都得到了很好的证实,当断点走到下面这里CorsFilter的doFilterInternal方法中:

       //关键就是这里,在这里打上断点if (!isValid || CorsUtils.isPreFlightRequest(request)) {return;}

    问题就出在如下代码:

CorsUtils.isPreFlightRequest(request)

    这行代码返回了true,就return了,后面的所有过滤器都没有执行,所以请求不到接口,浏览器还是在报跨域的问题,然后我就调试了CorsUtils.isPreFlightRequest(request)这行代码,发现是复杂请求跨域发了预检测请求(OPTIONS请求)之后Orgin会被设置了一个莫名奇妙的是:

http://localhost:3000

    这个就很奇怪了,然后我就找了前端同事老王帮看了下,这个值是哪里设置的,然后发现如下:

cors调试图片3

    前端没有设置Orgin,只是设置了如下参数:

//设置axios跨域访问
axios.defaults.withcredentials = true // 设置cross跨域 并设置访问权限 允许跨域携带cookie信息axios.defaults.crossDomain=true //设置axios跨域的配置

    上面的图片只有一个Referer的值跟Orgin的值不谋而合,难道这真的只是一个巧合,于是我参看了如下文章:

https://blog.csdn.net/qq_55316925/article/details/128571809

    给我很多的思路,那我想了一下,居然这样,后端配置的CustomCorsFilter是生效了的,那可不可以改CorsFilter源码,于是就尝试了下面两种方式,进过我和前端老王的验证,这两种方式都是可行的,任选一种都是可以解决cors跨域问题。

3.解决方法

3.1 方式一:后端修改CorsFilter源码

    后端修改CorsFilter源码

    在项目下src.main.java下新增一个org.springframework.web.filter的包

    然后将CorsFilter的源码拷贝出来,放到上面新建的这个org.springframework.web.filter的包下,就可以修改CorsFilter的源码了,

/** Copyright 2002-2019 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      https://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.web.filter;import java.io.IOException;import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.util.Assert;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsProcessor;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.DefaultCorsProcessor;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;/*** {@link javax.servlet.Filter} that handles CORS preflight requests and intercepts* CORS simple and actual requests thanks to a {@link CorsProcessor} implementation* ({@link DefaultCorsProcessor} by default) in order to add the relevant CORS* response headers (like {@code Access-Control-Allow-Origin}) using the provided* {@link CorsConfigurationSource} (for example an {@link UrlBasedCorsConfigurationSource}* instance.** <p>This is an alternative to Spring MVC Java config and XML namespace CORS configuration,* useful for applications depending only on spring-web (not on spring-webmvc) or for* security constraints requiring CORS checks to be performed at {@link javax.servlet.Filter}* level.** <p>This filter could be used in conjunction with {@link DelegatingFilterProxy} in order* to help with its initialization.** @author Sebastien Deleuze* @since 4.2* @see <a href="https://www.w3.org/TR/cors/">CORS W3C recommendation</a>*/
public class CorsFilter extends OncePerRequestFilter {private final CorsConfigurationSource configSource;private CorsProcessor processor = new DefaultCorsProcessor();/*** Constructor accepting a {@link CorsConfigurationSource} used by the filter* to find the {@link CorsConfiguration} to use for each incoming request.* @see UrlBasedCorsConfigurationSource*/public CorsFilter(CorsConfigurationSource configSource) {Assert.notNull(configSource, "CorsConfigurationSource must not be null");this.configSource = configSource;}/*** Configure a custom {@link CorsProcessor} to use to apply the matched* {@link CorsConfiguration} for a request.* <p>By default {@link DefaultCorsProcessor} is used.*/public void setCorsProcessor(CorsProcessor processor) {Assert.notNull(processor, "CorsProcessor must not be null");this.processor = processor;}@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {CorsConfiguration corsConfiguration = this.configSource.getCorsConfiguration(request);boolean isValid = this.processor.processRequest(corsConfiguration, request, response);//修改的源码是将CorsUtils.isPreFlightRequest(request)这行代码移除,就是因为复杂请求跨域发了预检测请求,浏览器的referrer-policy引用者策略会携带一个值,后端处理之后会将这个值赋值给请求头的Orgin属性上,移除这行代码之后就可以正常访问到登录接口了,前端也没有报跨域了。if (!isValid) {return;}filterChain.doFilter(request, response);}}

3.2 方式二:前端禁用或移除浏览器referrer-policy引用者策略

    前端新增如下代码 :禁用或者是移除referrer-policy`这个引用者策略

https://blog.csdn.net/qq_49810363/article/details/111036180

    新增代码如下:

<meta name="referrer" content="never">

cors调试图片4

    浏览器的referrer-policy引用者策略,也是为了安全考虑,我使用的浏览器是chrome浏览器

4.总结

    经过不断地尝试和摸索之后,对这个在项目中集成了sa-token后部署出现cors跨域的问题,总的来说是cors跨域协议的规范不允许这种操作,在加上浏览器和后端的解决库都不允许不遵循cors跨域协议的规范的请求操作,所以可以使用sa-token前后端分离解决跨域的正确姿势文章里面的方法,配置一个SimpleCORSFilter,对参数都写具体,处理预检测请求返回200状态码,或者使用本篇文章的这两种方式的任意一种都可以解决cors跨域的问题,本文的解决方法是我经过亲自打断点复现跨域请求之后debug出来的解决方法,如果你相信可以按照本文的方法,本地复现跨域请求然后dubug打断点,看一下是不是corsFilter的CorsUtils.isPreFlightRequest(request)这行代码的问题,总的来说,这个cors的跨域问题是浏览器要背的一个大锅,简单请求corsFilter是不会失效的,复杂请求发了预检测请求(OPTIONS请求),由于浏览器的referrer-policy引用者策略会携带一个值,后端处理之后会将这个值赋值给请求头的Orgin属性上,导致corsFilter的CorsUtils.isPreFlightRequest(request)这行代码返回true之后就return了,导致后面的一系列的Filter的doFilter没有执行到,也没有访问到后端的接口,而前端浏览器页面还在报跨域的问题,这个问题说实话是真的坑啊。https的方式跨域不行,因为https是监听443端口,是需要证书的,这个我猜测是要配置证书才可以的,本文洗白了集成sa-token之后会导致corsFilter配置失效的罪名啊,网上千篇一律的文章都没有本文的这种情况下的解决方法的,应该来说还是首创吧,创作不易,请尊重作者原创,请不要抄袭当做原创,请转载添加上原创出处,本次分享到此结束,希望我的分享对你有所启发和帮助,请一键三连,么么哒!

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • uboot学习:(三)目录分析
  • vue对axios进行请求响应封装
  • 多输入多输出 | Matlab实现Transformer多输入多输出预测
  • 全网最适合入门的面向对象编程教程:14 类和对象的 Python 实现-类的静态方法和类方法,你分得清吗?
  • 视频调整帧率、分辨率+音画同步
  • 丑数问题,力扣264,坑点
  • markdown文件转pdf
  • 了解AsyncRotationController
  • 【C语言】C语言-身份证管理系统(源码+注释)【独一无二】
  • mybatis日志记录方案
  • 解决vue多层弹框时存在遮挡问题
  • 新质生产力赛道核心解读,机械制造何以“向智向新”
  • 深入理解Spring Cloud中的服务注册
  • Docker Desktop如何换镜像源?
  • jdevelope安装
  • 深入了解以太坊
  • 【407天】跃迁之路——程序员高效学习方法论探索系列(实验阶段164-2018.03.19)...
  • ECMAScript入门(七)--Module语法
  • golang中接口赋值与方法集
  • React中的“虫洞”——Context
  • scrapy学习之路4(itemloder的使用)
  • vue+element后台管理系统,从后端获取路由表,并正常渲染
  • 对JS继承的一点思考
  • 基于 Babel 的 npm 包最小化设置
  • 记录:CentOS7.2配置LNMP环境记录
  • 精益 React 学习指南 (Lean React)- 1.5 React 与 DOM
  • 力扣(LeetCode)21
  • 如何在GitHub上创建个人博客
  • 入门到放弃node系列之Hello Word篇
  • 数据科学 第 3 章 11 字符串处理
  • 数据库写操作弃用“SELECT ... FOR UPDATE”解决方案
  • 通过几道题目学习二叉搜索树
  • 物联网链路协议
  • 用mpvue开发微信小程序
  • kubernetes资源对象--ingress
  • ​软考-高级-系统架构设计师教程(清华第2版)【第15章 面向服务架构设计理论与实践(P527~554)-思维导图】​
  • # Apache SeaTunnel 究竟是什么?
  • (1)SpringCloud 整合Python
  • (DenseNet)Densely Connected Convolutional Networks--Gao Huang
  • (SpringBoot)第二章:Spring创建和使用
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (补充):java各种进制、原码、反码、补码和文本、图像、音频在计算机中的存储方式
  • (超简单)构建高可用网络应用:使用Nginx进行负载均衡与健康检查
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (附源码)基于SpringBoot和Vue的厨到家服务平台的设计与实现 毕业设计 063133
  • (七)Java对象在Hibernate持久化层的状态
  • (十八)SpringBoot之发送QQ邮件
  • (图)IntelliTrace Tools 跟踪云端程序
  • (学习日记)2024.01.09
  • (已解决)Bootstrap精美弹出框模态框modal,实现js向modal传递数据
  • .net core开源商城系统源码,支持可视化布局小程序
  • .Net Core与存储过程(一)
  • .NET 将多个程序集合并成单一程序集的 4+3 种方法
  • .NET/ASP.NETMVC 大型站点架构设计—迁移Model元数据设置项(自定义元数据提供程序)...
  • .net中应用SQL缓存(实例使用)