[英]Block the app in mounted() until the user is authenticated using Amazon cognito and Vue.js
我使用以下代碼在 Vue.js 應用程序中使用Amazon Cognito對用戶進行身份驗證:
export default new Vue({
mounted() {
store.dispatch('authenticateUser', { email: 'username', password: 'password' }).then(() => {
if (store.state.cognito.authenticated) {
// Add authentication token to each request
axios.interceptors.request.use(async config => {
const response = await store.dispatch('getUserSession');
if (response && response.accessToken && response.accessToken.jwtToken) {
config.headers.AccessToken = response.accessToken.jwtToken;
}
return config;
});
} else {
this.flashError('AWS user is not authenticated.');
}
}).catch((err) => {
this.flashError(`AWS authentication error: ${err.message}`);
});
},
}).$mount('#app');
首先,我啟動異步身份驗證用戶操作,完成后我以某種方式設置axios ,所有axios請求都會自動將身份驗證信息發送到服務器。
我唯一還沒有弄清楚的是如何讓應用程序中的所有axios請求等待異步身份驗證完成。 (例如,當異步身份驗證仍在進行時,主應用程序頁面可以觸發axios請求以填充其數據,因此應該有某種機制使其等待)。
在其他語言(例如 C++ 或 C#)中,有兩種選擇: 1. 在 mount() 中阻止應用程序,直到身份驗證完成。 2. 使所有請求等待完成事件。
JavaScript 呢?
為了實現我嘗試過的第一個場景
await store.dispatch('authenticateUser', { email: 'username', password: 'password' }).then(() => {
但這不能編譯。
EDIT1: store.dispatch 真的是異步的嗎?
EDIT2:我嘗試將“異步”添加到mounted()。 這是朝着正確方向邁出的一步嗎?
async mounted() {
await store.dispatch('authenticateUser', { email: 'username', password: 'password' }).then(() => {
....
},
我想您有一個包含某些內容的應用程序,並且您只想允許經過身份驗證的用戶訪問,否則您會將錯誤的用戶重定向到另一個頁面,我建議按以下方式進行
import Vue from 'vue';
import VueRouter from 'vue-router';
import Vuetify from 'vuetify';
import Vuex from 'vuex';
import axios from 'axios';
import VueAxios from 'vue-axios';
import store from './index'
Vue.use(Vuetify);
Vue.use(VueRouter);
Vue.use(Vuex);
Vue.use(VueAxios, axios);
var myapp=null;
store.dispatch('authenticateUser', { email: 'username', password: 'password' }).then(() => {
if (store.state.cognito.authenticated) {
// Add authentication token to each request
axios.interceptors.request.use(async config => {
const response = await store.dispatch('getUserSession');
if (response && response.accessToken && response.accessToken.jwtToken) {
config.headers.AccessToken = response.accessToken.jwtToken;
myapp=new Vue({}).$mount('#app');//the right app
}
return config;
});
} else {
this.flashError('AWS user is not authenticated.');
myapp=new Vue({}).$mount('#app');//app that contains warnings
}
}).catch((err) => {
this.flashError(`AWS authentication error: ${err.message}`);
myapp=new Vue({}).$mount('#app');//app that contains warnings
});
因此,如果響應正常,您將創建一個包含正確內容的Vue
實例
myapp=new Vue({}).$mount('#app');
否則將該用戶重定向到包含警告的應用程序
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.