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

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

我正在开发一个使用rails作为Backend API和vue.js作为前端库的Web应用程序。在身份验证期间,我使用devise_token_auth库。现在它似乎是在响应的标题内发送令牌信息,我不知道如何使用javascript进行检索。

我还展示了他们有单独的库,如J-tokerng-token-authangular2-token ..etc从他们我跟随jtoker auth因为我想使用vue.js。但它似乎需要React组件。在这里,我附上了使用Postman的回复。

回应机构:

{"data":{"id":3,"email":"[email protected]","provider":"email","uid":"[email protected]","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 →[email protected]
javascript ruby-on-rails authentication devise vue.js
1个回答
1
投票

您需要拦截所有请求/响应调用并使用access-token包含/检索标头。配置标头可以保存在浏览器的localstorage中以维护连接。

您可以使用任何基于promise的http客户端来实现此目的,对于下面的示例,我将使用axios

您首先需要在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)
});
© www.soinside.com 2019 - 2024. All rights reserved.