【问题标题】:Javascript/Rails authorization fetch headersJavascript/Rails 授权获取标头
【发布时间】:2016-09-14 19:39:24
【问题描述】:

所以我正在开发 React/Redux SPA 应用程序,并且我想要授权工作。我有使用 devise_token_auth gem 工作的 Rails 后端,并且(在 React 应用程序中)我需要保存一个由后端响应我的令牌。但是,response.headers 没有可用的令牌。为什么? CORS 在后端正确设置,所以我确定这不是问题。看一下代码和截图:

let config = {
  method: 'POST',
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify(creds) // { email: 'asd@example.org', password: 'asdasdasd' }
}

return dispatch => {
  dispatch(requestLogin(creds))
  return fetch('http://localhost:3000/auth/sign_in', config)
    .then((response => {
      response.headers.forEach((el) => console.log(el))
    }))
}

console.log:

证明浏览器可以看到标题:

【问题讨论】:

  • 我建议只在 sign_in 响应正文中返回令牌,而不是尝试将其添加到标头中。从安全的角度来看没有任何好处。
  • @BlairAnderson 我使用 devise-token-auth,但我找不到配置选项(我不想猴子补丁)。尽管如此,看不到 JS 中的所有标题还是很奇怪的,我会先解决这个问题。但是感谢重播:)

标签: javascript authentication token fetch


【解决方案1】:

已修复。问题出在后端。我在我的 rack-cors 初始化程序中有这个:

headers: :any,                                                                                                         
methods: [:get, :post, :put, :patch, :delete, :options, :head]

改成这样:

headers: :any,
expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :put, :patch, :delete, :options, :head]                                                                                               

现在一切正常 :) 查看 devise_token_auth 的源代码时得到它。

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 2018-04-17
    • 2016-07-13
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多