设计令牌身份验证-如何使用javascript访问响应头信息?

设计令牌身份验证-如何使用javascript访问响应头信息?,javascript,ruby-on-rails,authentication,devise,vue.js,Javascript,Ruby On Rails,Authentication,Devise,Vue.js,我正在开发一个web应用程序,使用rails作为后端API,vue.js作为前端库。为此,在身份验证过程中,我使用库。现在,它似乎正在响应头中发送令牌信息,我不知道如何使用javascript检索 我还展示了他们有独立的图书馆, ,等等,我跟随jtoker auth,因为我想使用vue.js。但这似乎需要反应成分。这里我附上的答复,我得到使用邮递员 答复机构: {"data":{"id":3,"email":"contact@dazzlebirds.com","provider":"email"

我正在开发一个web应用程序,使用rails作为后端API,vue.js作为前端库。为此,在身份验证过程中,我使用库。现在,它似乎正在响应头中发送令牌信息,我不知道如何使用javascript检索

我还展示了他们有独立的图书馆, ,等等,我跟随jtoker auth,因为我想使用vue.js。但这似乎需要反应成分。这里我附上的答复,我得到使用邮递员

答复机构:

{"data":{"id":3,"email":"contact@dazzlebirds.com","provider":"email","uid":"contact@dazzlebirds.com","name":null,"image":null}}
响应标题:

Cache-Control →max-age=0, private, must-revalidate
Content-Type →application/json; charset=utf-8
ETag →W/"2af9684eadab13f0efebb27b8e29a7be"
Transfer-Encoding →chunked
Vary →Origin
X-Content-Type-Options →nosniff
X-Frame-Options →SAMEORIGIN
X-Request-Id →41f3df67-574c-4095-b471-a8fd08b85be5
X-Runtime →0.768768
X-XSS-Protection →1; mode=block
access-token →DGoclk9sbb_LRgQrr5akUw
client →7_Lfy0RlEbzkpLOpiQCKRQ
expiry →1516322382
token-type →Bearer
uid →contact@dazzlebirds.com

您需要截获所有请求/响应调用,并包含/检索带有访问令牌的标头。配置头可以保存在浏览器的localstorage中以维护连接

您可以使用任何基于承诺的http客户端来实现这一点,例如下面我将使用的示例

首先需要在vue应用程序的main.js文件中导入axios

import axios from 'axios'
然后,您可以根据需要拦截请求

axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.interceptors.request.use(function (config) {
  const authHeaders = JSON.parse(window.localStorage.getItem('authHeaders'))
  if(authHeaders) {
    config.headers[config.method] = {
      'access-token': authHeaders['access-token'],
      'client': authHeaders['client'],
      'uid': authauthHeadersUser['uid']
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error)
});

axios.interceptors.response.use(function (response) {
  if(response.headers['access-token']) {
    const authHeaders = {
      'access-token': response.headers['access-token'],
      'client': response.headers['client'],
      'uid': response.headers['uid'],
      'expiry': response.headers['expiry'],
      'token-type': response.headers['token-type']
    }
    window.localStorage.setItem('authHeaders', JSON.stringify(authHeaders));
  } else {
    window.localStorage.removeItem('authHeaders');
  }
  return response;
}, function (error) {
  return Promise.reject(error)
});

JWT比这要好得多gem@7urkm3n你能和我分享一下这个宝石的链接吗?因为还有其他的jwt基本宝石可以完美地工作!我不知道这一点,最终修改了designe_token_auth gem的响应,以在响应体中发送身份验证头值,但这肯定是一种方法。