[英]Pass token from API to front-end during redirect
我在Node.js中有一個后端,在Vue.js中有一個前端,並且有這樣的場景:
API-1:檢索用戶令牌並重定向到API-2。 令牌應沿着API-2發送
API-2:顯示一個網頁,其中填充了取決於API-1中生成的令牌的數據。 令牌本身應被訪問,如果可能,應將其存儲在客戶端(瀏覽器)的本地存儲中。
因此,在重定向期間,我需要將令牌從后端傳遞到客戶端。 我寧願不將其作為查詢參數發送,因為那意味着任何人都可以看到它。
API-1內容:
....
var api_2_uri = "/";
var user_token = get_token_function(); //user token was retrieved
res.redirect(api_2_uri); //todo: send user_token along the request for redirect
API-2(重定向頁面)的內容:
....
<p>{{username}}</p>
<p>{{email}}</p>
<p>{{telephone}}</p>
<script src="./vue_code.js"></script>
....
Vue.js代碼(vue_code.js):
var login_form = new Vue({
el: '#login_form',
data: {
username: "",
email: "",
telephone: ""
},
created(){
var user_token_value = ""; //todo: here we must access the user token that was passed to the front-end app. if possible, store it in the app's local storage
fetch('https://third_party_url?user_token='+user_token_value)
.then(response => response.json())
.then(json => {
this.username = json.username;
this.email = json.email;
this.telephone = json.telephone;
})
}
})
我到處搜索了,對於客戶端,將令牌保存在本地存儲中的想法似乎是最好的。 然而:
我更喜歡簡單的解決方案,因為對於此代碼而言,使用大量的庫/模塊將是一個過大的選擇。
要將數據臨時存儲在瀏覽器中,可以使用本地存儲或會話存儲 ,在這種情況下,可以使用本地存儲或會話 存儲 npm
例如,在本地存儲中設置令牌:
var ls = require('local-storage');
// when user signed in you give them a token
var user_token = generate_token-function();
ls.set('foo', user_token);
// then to verify the token, you can use a get method
var getUserToken = ls.get('foo')
// then you can verify it :
verifyToken_function(getUserToken) /* if (err) redirect the user to your login page res.redirect('/login') else everything is good res.redirect('/profile) */
您可以使用jQuery的AJAX請求進行操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.