Javascript 如何检查令牌过期和注销用户?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44982412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i check for token expiration and logout user?
提问by Serenity
The user can logout himself when he/she clicks on the logout button but if the token is expired he/she cant logout because in my application, the token is used in both server side and front end. When user clicks on the logout button, the token from both server and browser is cleared if token is valid. There is a chance that when user does not log out and his/her token expires but is not being cleared in the browser. For addressing this situation, how do i check for token expiration every time the user visits in my app so if the token is expired, clear the token from the browser?
用户可以在他/她单击注销按钮时注销自己,但是如果令牌过期,他/她无法注销,因为在我的应用程序中,令牌用于服务器端和前端。当用户单击注销按钮时,如果令牌有效,来自服务器和浏览器的令牌将被清除。有可能当用户没有注销并且他/她的令牌过期但没有在浏览器中被清除时。为了解决这种情况,每次用户访问我的应用程序时,我如何检查令牌是否过期,以便如果令牌已过期,请从浏览器中清除令牌?
I tried in saga which watches in the background every time the user refreshes in the page or switch to another page. I don't think this is an efficient way. I reckon middleware comes into play.
我在 saga 中尝试过,每次用户刷新页面或切换到另一个页面时,它都会在后台观看。我不认为这是一种有效的方式。我认为中间件开始发挥作用。
function* loadInitialActions() {
var dateNow = new Date();
console.log(jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat);
const token =
JSON.parse(localStorage.getItem("user")) &&
JSON.parse(localStorage.getItem("user"))["token"];
if (
token &&
jwtDecode(token).exp < dateNow.getTime() - jwtDecode(token).iat
) {
yield put(LOGOUT_SUCCESS);
}
}
function* initialize() {
const watcher = yield fork(loadInitialActions);
yield take([INITIALIZE_ERROR, INITIALIZE_SUCCESS]);
yield cancel(watcher);
}
function* rootSaga() {
console.log("rootSaga");
yield takeLatest(INITIALIZE, initialize);
}
So my question is how do i use the token expiration logic and logout user if token is expired from the middleware?
所以我的问题是如果令牌从中间件过期,我如何使用令牌过期逻辑和注销用户?
回答by Tushant
In my view middleware will be the best option.
在我看来,中间件将是最好的选择。
You can do something like this
你可以做这样的事情
const checkTokenExpirationMiddleware = store => next => action => {
const token =
JSON.parse(localStorage.getItem("user")) &&
JSON.parse(localStorage.getItem("user"))["token"];
if (jwtDecode(token).exp < Date.now() / 1000) {
next(action);
localStorage.clear();
}
next(action);
};
You have to then wrap it in applyMiddleware
然后你必须把它包起来 applyMiddleware
回答by vijayst
You need to wrap the Main component with a HOC. The HOC will validate the token and if OK allow the component to display. If the token is invalid, the login page is redirected to.
您需要使用 HOC 包装 Main 组件。HOC 将验证令牌,如果OK 则允许组件显示。如果令牌无效,登录页面将被重定向到。
const authChecker = (Component) => {
return class extends React.Component {
state = {
show: false;
}
componentWillReceiveProps(nextProps) {
if (nextProps.children !== this.props.children) {
this.checkAuth();
}
}
componentDidMount() {
this.checkAuth();
}
checkAuth() {
Api.checkAuth()
.then(result => {
if (result.success) {
this.setState({ show: true });
} else {
// logout since token expired
API.logout();
}
});
}
render() {
return this.state.show && <Component {...this.props} />
}
}
}
export default authChecker(Main);
回答by jonathana
this.serverResponse.expires_inis the expiration time in seconds.
this.serverResponse.expires_in是以秒为单位的过期时间。
var tokenexpiration: Date = new Date();
tokenexpiration.setSeconds(new Date().getSeconds() + parseInt(this.serverResponse.expires_in))
console.log(tokenexpiration);
than you can save it to localStorage:
比您可以将其保存到 localStorage:
localStorage.setItem('expirationdate',tokenexpiration)
and with simple condition you can check whenever you need if the token was expired.
并且通过简单的条件,您可以在需要时检查令牌是否已过期。

