【问题标题】:Vue two requests only one valid tokenvue 两次只请求一个有效token
【发布时间】:2017-01-11 10:47:48
【问题描述】:

我刚开始使用 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 令牌之前,两个请求都是并行触发的。 所以我的问题是,如何强制第二个请求直到第一个请求完全完成,或者如何强制拦截器等待?

【问题讨论】:

    标签: jwt vue.js vue-resource


    【解决方案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 Example Project 或更具体的Auth.js 文件,了解我是如何实现刷新令牌功能的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      相关资源
      最近更新 更多