基于令牌的身份验证中的会话 [英] Sessions in token based authentication
问题描述
我正在用PHP Lumen构建一个应用程序,该应用程序在登录时会返回一个令牌.我不知道如何继续进行.
I am building an app in PHP Lumen which returns a token upon login. I am not sure how to proceed beyond this.
我应该如何使用这些令牌维护会话?
How am I supposed to maintain a session using these tokens?
具体来说,如果我使用reactjs或原始HTML/CSS/jQuery,如何将令牌存储在客户端,并在我为Web应用程序的安全部分提出的每个请求中发送令牌?
Specifically, how do I store the tokens on the client side if I am using reactjs or vanilla HTML/CSS/jQuery and send them in every request I make for the secure part of my web app?
推荐答案
我通常要做的是将令牌保留在本地存储中,这样即使用户离开站点,我也可以保留令牌.
What I usually do is to keep the token in the local storage, this way I can persist the token even if the user leaves the site.
localStorage.setItem('app-token', theTokenFromServer);
每次用户加载页面时,我要做的第一件事就是寻找令牌的存在.
Every time the user loads the page, the first thing I do is to look for the existence of the token.
token = localStorage.getItem('app-token');
如果使用react,我会将令牌保持在全局状态(例如,使用redux):
If using react, I'd keep the token on the global state (using redux for example):
function loadAppToken(token) {
return {
type: 'LOAD_TOKEN',
payload: { token },
};
}
使用香草javascript,可以将其保留在我的连接实用程序中.可能类似于以下内容:
With vanilla javascript I'd keep it on my connection utility. Which might look something like the following:
const token = localStorage.getItem('app-token');
export function request(config) {
const { url, ...others } = config;
return fetch(url, {
...others,
credentials: 'include',
headers: {
'Authorization': `Bearer ${token}`
},
});
}
与以前的代码类似,我仍然在react应用中有一个fetch实用程序,但是我会通过在redux中间件中为每个单个请求获取令牌,从而在选项中发送令牌.
I'd still have a fetch utility in a react app, similar to the previous code, but I'd send the token in the options, by getting it in a redux middleware for every single request.
这篇关于基于令牌的身份验证中的会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!