代码之家  ›  专栏  ›  技术社区  ›  Tim von Känel

当使用ajax请求时,某些cookie被跨域阻止

  •  0
  • Tim von Känel  · 技术社区  · 5 年前

    我正在使用一个运行在localhost:3000上的react应用程序,它向我们的网站发出ajax请求。我们最近将身份验证系统从使用wordpress身份验证转换为 https://github.com/delight-im/PHP-Auth

    从那时起,在ajax内部和web服务器上使用相同的设置,身份验证cookie不会跨域发送。但是,当从同一个域请求它们时,它可以工作。

    我们的要求:

    fetchLoginStatus = () => {
        const ajax = new XMLHttpRequest();
        ajax.withCredentials = true;
        ajax.open("POST", "https://our-website.com/src/php/checkLoggedIn.php");
        ajax.onload = () => {
          const response = JSON.parse(ajax.responseText);
        };
        ajax.send();   
    };
    

    我们的请求头(来自localhost:3000):

    :authority: my-website.com
    :method: POST
    :path: /src/php/checkLoggedIn.php
    :scheme: https
    accept: */*
    accept-encoding: gzip, deflate, br
    accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
    content-length: 0
    cookie: plesk-items-per-page; plesk-sort-field, phpMyAdmin; databases-active-list-state-collapsed; plesk-list-type; io=R_dL3fjUEYe64ykHAAAp; isAsyncProgressBarCollapsed=true; PLESKSESSID; plesk-sort-dir;
    origin: https://localhost:3000
    referer: https://localhost:3000/
    

    我们的响应头(我们运行的是nginx服务器):

    access-control-allow-credentials: true
    access-control-allow-headers: origin, x-requested-with, content-type 
    access-control-allow-methods: PUT, GET, POST, DELETE, OPTIONS access-` 
    control-allow-origin: https://localhost:3000 
    cache-control: no-store, no-cache, must-revalidate 
    content-encoding: br  
    content-type: text/html; charset=UTF-8 
    date: Sun, 10 Mar 2019 15:26:08 GMT 
    expires: Thu, 19 Nov 1981 08:52:00 GMT pragma: 
    no-cache server: nginx 
    set-cookie: PHPSESSID=someId; 
    path=/; SameSite=Lax status: 200 
    vary: Accept-Encoding 
    x-powered-by: PleskLin`
    

    当我不发送跨域请求时,phpsessid在我请求头的cookies中。但是,当我从localhost:3000发送请求时,它不在那里。

    有人知道我如何从本地主机发送phpsessid吗?

    谢谢你的帮助!

    0 回复  |  直到 5 年前
        1
  •  0
  •   Tim von Känel    5 年前

    在github存储库中问了同样的问题,所有者解决了这个问题。

    https://github.com/delight-im/PHP-Auth/issues/154

    解决方案:

    供应商/delight im/auth/src/usermanager.php

    Replace Session::regenerate(true); with Session::regenerate(true, null);
    

    供应商/delight im/auth/src/auth.php

    Replace @Session::start(); with @Session::start(null);
    Replace Session::regenerate(true); with Session::regenerate(true, null);
    After $cookie->setSecureOnly($params['secure']); append $cookie- 
    >setSameSiteRestriction(null); in all three (!) occurrences