【问题标题】:Cookie not being sent back to the server when making API requests发出 API 请求时未将 Cookie 发送回服务器
【发布时间】:2020-05-10 22:42:11
【问题描述】:

我正在使用 React 前端在 Rails 中开发 API。我正在连接身份验证,但我忘记了一些事情。对 /api/v1/me 的第一个请求应该得到 401,然后我进行身份验证并获得 cookie,但是当我向 /api/v1/me 发出第二个请求时,cookie 没有被发送。我过去做过这项工作,但我似乎忘记了如何。

我在服务器上使用 Rails 6.0.2.2,我确实尝试添加这个初始化文件:

Rails.application.config.session_store :cookie_store, key: 'session', domain: :all

我已经(暂时)启用了 CORS:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "*"
    resource "*", headers: :any, methods: :any
  end
end

【问题讨论】:

  • 可能是 CSRF 令牌问题?

标签: ruby-on-rails api cookies


【解决方案1】:

我找到了答案。我需要在我的 CORS 设置中有 credentials: true,所以,像这样:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "localhost:3000"

    # resource "/api/*", headers: %w[Authorization], methods: :any, expose: %w[Authorization], max_age: 600
    # resource "*", headers: :any, methods: :any
    resource "/api/v1/*",
             headers:     %w[Authorization],
             methods:     :any,
             credentials: true,
             expose:      %w[Authorization],
             max_age:     600
  end
end

我还需要在发出请求时将withCredentials: true 传递给axios:

axios.get(`${apiEndPoint()}/me`, {withCredentials: true})

【讨论】:

    猜你喜欢
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 2021-05-29
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多