2016-09-03 25 views
0

我剛開始使用vue和vue資源。 在後端我使用laravel,在那裏處理jwt令牌。 令牌每刷新一次請求。到目前爲止,一切進展順利,除了一種情況: 如果我連續發出兩個請求與VUE資源象下面這樣: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令牌。 所以我的問題是,我如何強制第二個請求,直到第一個完全完成,或者我該如何強制攔截器等待?

回答

1

我不認爲你可以用攔截器來完成這件事,就像你擁有它一樣。承諾是異步的。您需要將第二個請求放入第一個請求的成功回調中。但是,我認爲這會在某些時候造成不必要的混亂,並且會從通話中消除異步功能。

我認爲更好的解決方案是在您的後端API(Laravel/Passport)中創建專門用於刷新令牌的端點。您需要發送一個refresh_token到端點以獲取新的access_token。讓訪問令牌活得更長(這樣您就不會讓它們過於沉重,而且會讓應用程序變慢)。這是一個典型的OAuth2流程。這裏有一個攔截器(VueJS 2.0和最新的Vue資源1.0.3),將添加您的驗證頭,並自動刷新令牌時攔截變得無效令牌響應:

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文件,看看我是如何實現刷新令牌功能的。

相關問題