React向Spring Boot传递Cookie授权令牌并设置X-auth头的方法
前端传at_origin到SpringBoot的实现方案
核心逻辑调整说明
目前你只开启withCredentials: true的配置,只会让浏览器把符合跨域规则的全量Cookie自动带给后端,不会自动提取at_origin的特定值放到自定义X-auth请求头中,需要分前后端两侧调整逻辑完成传值和取值。
前端侧调整步骤
- 实现Cookie值读取逻辑
先通过原生WebAPI从浏览器存储中提取at_origin对应的值,可以复用通用的Cookie读取工具:// 提取Cookie中指定键的值 const getCookie = (keyName) => { const cookieList = document.cookie.split('; '); const targetItem = cookieList.find(item => item.startsWith(`${keyName}=`)); return targetItem ? decodeURIComponent(targetItem.split('=')[1]) : ''; } - 调整axios调用的配置
在调用auth_status接口时,把读取到的at_origin值放到X-auth请求头中,同时保留原有的跨域带Cookie配置:export const userAuthStatus = async () => { // 读取Cookie中的at_origin值 const atOriginValue = getCookie('at_origin'); const authStatus = await axios.post( 'https://你的后端服务地址/auth_status', { resources: [{ classpath: 'test' }] }, { // 保留跨域自动携带Cookie的配置 withCredentials: true, // 新增X-auth自定义请求头 headers: { 'X-auth': atOriginValue } } ).then(response => response.data.user); return authStatus; };
跨域注意:因为新增了
X-auth自定义请求头,SpringBoot侧的CORS跨域配置需要把X-auth加入允许的请求头列表,否则浏览器会直接拦截跨域请求。
SpringBoot后端侧取值实现
根据你实际的传值方式,可以选择两种对应的取值方案:
方案1:从X-auth请求头取值(对应前端手动塞头的传值方式)
在接口方法中通过@RequestHeader注解直接提取对应请求头的值:
@PostMapping("/auth_status") public Object validateAuth( // 直接读取X-auth请求头中传的at_origin值 @RequestHeader("X-auth") String atOrigin, // 接收前端传的请求体参数 @RequestBody AuthCheckRequest request ) { // 直接用atOrigin做认证校验逻辑即可 return "校验通过"; }
方案2:从Cookie中直接取值(对应仅靠withCredentials自动带Cookie的传值方式)
如果前端没有手动设置X-auth头,浏览器自动全量携带Cookie到后端后,可以通过@CookieValue注解直接提取对应Cookie值,不需要手动解析Cookie字符串:
@PostMapping("/auth_status") public Object validateAuth( // 直接从请求的Cookie中提取at_origin值 @CookieValue("at_origin") String atOrigin, @RequestBody AuthCheckRequest request ) { // 直接用atOrigin做认证校验逻辑即可 return "校验通过"; }
补充注意事项
- 如果
at_origin这个Cookie在前端存储时设置了HttpOnly属性,前端的JS脚本是无法通过document.cookie读取到这个值的,这种场景下不需要做前端提取放请求头的操作,直接在后端用@CookieValue读取即可,不会影响认证逻辑 - 跨域开启
withCredentials时,SpringBoot的CORS配置不能把允许的源设为*,必须指定具体的前端访问域名,同时要开启allowCredentials(true)配置,否则浏览器会拦截携带凭证的跨域请求
内容的提问来源于stack exchange,提问作者Rhea
相关产品推荐
相关产品推荐

