[英]Pass token from API to front-end during redirect
I have a back-end in Node.js, front-end in Vue.js and a scenario like this: 我在Node.js中有一个后端,在Vue.js中有一个前端,并且有这样的场景:
API-1: Retrieves a user token and redirects to API-2. API-1:检索用户令牌并重定向到API-2。 The token should be sent along API-2
令牌应沿着API-2发送
API-2: Displays a web page, populated with data that depend from the token generated in API-1. API-2:显示一个网页,其中填充了取决于API-1中生成的令牌的数据。 The token itself should be accessed and if possibly stored in the client's (browser's) local storage.
令牌本身应被访问,如果可能,应将其存储在客户端(浏览器)的本地存储中。
So during the redirect I need to pass the token from the back-end to the client side. 因此,在重定向期间,我需要将令牌从后端传递到客户端。 I would rather not send it as a query param because that would mean that anyone can see it.
我宁愿不将其作为查询参数发送,因为那意味着任何人都可以看到它。
API-1 content: 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 (the redirected page) content: API-2(重定向页面)的内容:
....
<p>{{username}}</p>
<p>{{email}}</p>
<p>{{telephone}}</p>
<script src="./vue_code.js"></script>
....
Vue.js code (vue_code.js): 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;
})
}
})
I have searched around and for the client side the idea of keeping the token in the local storage seems like the best. 我到处搜索了,对于客户端,将令牌保存在本地存储中的想法似乎是最好的。 However:
然而:
I would prefer simplistic solutions, since for the scope of this code using multitudes of libraries/modules would be an overkill. 我更喜欢简单的解决方案,因为对于此代码而言,使用大量的库/模块将是一个过大的选择。
To store data temporarily in the browser you can use local storage or session storage , in that case you can use a local-storage or sessionstorage npm 要将数据临时存储在浏览器中,可以使用本地存储或会话存储 ,在这种情况下,可以使用本地存储或会话 存储 npm
for example, to set a token in local storage : 例如,在本地存储中设置令牌:
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) */
You can alos do it with AJAX request from jQuery 您可以使用jQuery的AJAX请求进行操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.