未在SPA的浏览器中将Cookie设置为与API通信

问题描述 投票:1回答:1

我正在设置React SPA(www.mysite.com)和Rails API(api.mysite.com)应用。当我使用相同的URL名称时,一切都按预期工作,但是,当URL名称不同时,Web浏览器未设置站点cookie。由于缺少Cookie,CSRF验证当然也会失败。因此,例如,如果SPA应用程序在localhost上运行,而Rails API应用程序在localhost:3000上运行都很好,那么问题就出在我使用预期的DNS名称时。

听起来像是CORS问题,但现在很多天都找不到了……

这是我的配置:

我在使用rack-cors红宝石宝石时滑行

config / initializers / cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
   allow do
     origins 'localhost’,  'www.mysite.com',

     resource '*',
       headers: :any,
       credentials: true,
       methods: [:get, :post, :put, :patch, :delete, :options, :head]
   end
end

Rails.application.config.action_controller.forgery_protection_origin_check = false

在React端,我的axios配置如下:

src / App.js

axios.defaults.xsrfCookieName = "CSRF-TOKEN";
axios.defaults.xsrfHeaderName = "X-CSRF-Token";
axios.defaults.withCredentials = true;

React App启动时,它向API后端发出GET请求以获取CSRF令牌以供以后使用。同时应该使用浏览器设置站点cookie。

    axios
        .get("/sessions/csrf_token", {
          headers: { "Content-Type": "application/json"
          },
        })
        .then(response => {
          // do stuff
          });
        });

在设置和缺少站点cookie的两种情况下,响应头看起来都相同

enter image description here

我还可以看到Cookie已发送到浏览器,但它们在Cookie部分下仍然丢失

enter image description here

非常感谢您对我在这里可能缺少的任何想法!!!谢谢!!

更新:

我也应该提到我的会话配置文件设置为允许子域

config / initializers / session_store.rb

Rails.application.config.session_store :cookie_store, key: '_mysite_session', expire_after: 8.hours, domain: :all, tld_length: 2

可能我的cookie配置有其他问题,但是我不知道应该在哪里查看以及应该检查哪些其他设置。

这是我使用localhost时Cookie窗格的屏幕截图,并且Cookie会按预期保留在浏览器中:

enter image description here

[当我使用www.mysite.comapi.mysite.com名称时,右侧窗格只是空白。

我正在设置React SPA(www.mysite.com)和Rails API(api.mysite.com)应用。当我使用相同的URL名称时,一切都会按预期工作,但是,当URL名称不同时,Web浏览器不是...

ruby-on-rails cookies axios cross-domain csrf
1个回答
1
投票

我一直在研究,我认为这可能与您看到的内容有关:

© www.soinside.com 2019 - 2024. All rights reserved.