• axios跨域请求设置并携带Cookies


    axios跨域请求设置Cookies

    书接上回:《axios转发/oauth/authorize未设置cookies问题》
    上回实现了axios 在client域名下情趣oauth域名并使response返回Set-Cookies的header
    在这里插入图片描述
    但是,接下来在域名oauth.szile.com域名下请求接口时,请求没有携带设置的Cookie,这是问什么? 难道是没有设置成功?
    在这里插入图片描述
    查看Application下Cookie,确实是没有设置成功。
    在这里插入图片描述
    经过搜索查找说 axios的请求必须配置axios.defaults.withCredentials = true,并且Response的Header需要有Access-Control-Allow-Credentials: true。

    配置axios

    // 创建axios实例
    const service = axios.create({
      baseURL: process.env.VUE_APP_BASE_API, // api的base_url
      timeout: 0, // 请求超时时间
      withCredentials: true
    })
    // 或者
    // axios.defaults.withCredentials = true;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Response header中写返回了
    在这里插入图片描述
    但却报跨域错误
    在这里插入图片描述
    在这里插入图片描述
    从console信息「The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard '’ when the request’s credentials mode is ‘include’.」时说当请求是携带凭据模式(即Access-Control-Allow-Credentials: true、携带Cookie)时,Response的header “Access-Control-Allow-Origin” 的值不能是“” 通配符。

    经过需改配置

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {
    
        // *** 此处省略 *** 
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().configurationSource(httpServletRequest -> {
                final CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.setAllowedOrigins(List.of("*"));
                corsConfiguration.setAllowedHeaders(List.of("*"));
                corsConfiguration.setAllowCredentials(true);
    
                return corsConfiguration;
            });
            // *** 此处省略 *** 
        }
    }   
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    成功的设置Cookie
    在这里插入图片描述
    在这里插入图片描述

    总结

    1. 跨域请求是携带Cookie ,需要配置axios.defaults.withCredentials = true;
    2. 响应需要携带响应头 Access-Control-Allow-Credentials: true;
    3. 响应头 Access-Control-Allow-Origin 不能是通配符“*” ,并且需要和请求头Origin 的值一致。
  • 相关阅读:
    .NET的各种对象在内存中如何布局[博文汇总]
    第六章 将对象映射到 XML - 控制对象值属性的映射形式
    C#程序发布时,一定要好好地保护,不然你会后悔的
    【Linux】第十八站:进程等待
    Docker Compose和Consul
    Flink 中的 Window (窗口)
    深圳市罗湖、龙岗、南山等7各区的研发补贴汇总
    BSCNews报告:Sui网络近期数据激增,生态发展良好
    面向对象编程之断言assert
    分布式系列之分布式计算框架Flink深度解析
  • 原文地址:https://blog.csdn.net/weixin_39515823/article/details/127715530