0

我刚开始使用 vue 和 vue 资源。在后端,我使用 laravel,我在其中处理 jwt 令牌。每次请求都会刷新令牌。到目前为止,这很好用,除了一种情况:如果我使用 vue 资源连续发送两个请求,如下所示:

 //first request
 Vue.http.get('/api/runs').then((response) => {

        return response.json();
    }, (response) => {
        console.log(response);
        this.$set('error', {'status' : response.status, 'error': response.statusText});
    });
//second request
Vue.http.get('/api/meta').then((response) => {

        return response.json();
    }, (response) => {
        console.log(response);
        this.$set('error', {'status' : response.status, 'error': response.statusText});
    });

只有第一个请求具有有效令牌。我通过拦截器设置令牌:

 Vue.http.interceptors.push((request, next) => {
    request.headers['Authorization'] = Auth.getAuthHeader();
    request.emulateJSON = true;
    next(function(response) {
        if(response.headers['Authorization']) {
            var token = response.headers['Authorization'];
            localStorage.setItem('jwt-token', token);
        }
    });
});

发生这种情况是因为在拦截器可以设置新的 jwt 令牌之前,两个请求都是并行触发的。所以我的问题是,如何强制第二个请求直到第一个请求完全完成,或者如何强制拦截器等待?

4

1 回答 1

1

我认为您无法使用拦截器来完成此任务。Promise 是异步的。您需要将第二个请求放入第一个请求的成功回调中。但是,我认为这可能会在某些时候变得不必要的混乱,并且还会从您的通话中带走异步功能。

我认为更好的解决方案是在后端 API(Laravel/Passport)中创建一个端点,专门用于刷新令牌。您需要向refresh_token端点发送一个以取回您的新access_token. 让访问令牌的寿命更长(这样您就不会过于频繁地刷新它们并减慢您的应用程序的速度)。这是典型的 OAuth2 流程。这是一个拦截器(VueJS 2.0 和最新的 Vue-resource 1.0.3),它将添加您的 Auth 标头并在拦截器收到无效令牌响应时自动刷新令牌:

Vue.http.interceptors.push((request, next) => {
  const token = "get your token from localStorage or Vuex here"
  const hasAuthHeader = request.headers.has('Authorization')

  if (token && !hasAuthHeader) {
    request.headers.set('Authorization', 'Bearer ' + token)
  }

  next((response) => {
    if (response.status === 401 && response.data.error === 'invalid_token') {
      // Create this function below to get the new token and store
      // it in localStorage and then retries the original request.
      return refreshToken(request)
    }
  })
})

我会把这个refreshToken(request)函数留给你写,但希望你能在这里得到这个想法。您可以进行调整并使用 JWT。您可以查看我的VueJS 2.0 示例项目或更具体的Auth.js文件,了解我是如何实现刷新令牌功能的。

于 2016-11-01T18:04:58.967 回答