我使用了下面的超时代码。当我登录并保持非活动状态1小时后,超时成功,用户将注销。
但是当我登录并关闭浏览器,并在1小时后返回并在浏览器中打开应用程序时,会话仍然存在,用户仍然登录。
为什么我只能在应用程序处于打开和非活动状态时才能注销,如果我关闭浏览器并在1小时后返回,为什么不能注销?
import { Router } from '@angular/router';
import { AuthenticationService } from '../_services/authentication.service';
import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs';
const MINUTES_UNITL_AUTO_LOGOUT = 1 // in Minutes
const CHECK_INTERVALL = 1000 // in ms
const STORE_KEY = 'lastAction';
@Injectable({
providedIn: 'root'
})
export class AutoLogoutService {
isSuperadmin$ : Observable<boolean>;
isLoggedIn$ : Observable<boolean>;
islogin = false;
constructor(
private auth: AuthenticationService,
private router: Router,
private ngZone: NgZone
) {
this.isLoggedIn$ = this.auth.isUserLoggedIn;
this.isSuperadmin$ = this.auth.isSuperadmin;
this.lastAction(Date.now());
this.check();
this.initListener();
this.initInterval();
}
getlastAction() {
return localStorage.getItem('lastaction');
}
lastAction(value) {
localStorage.setItem('lastaction', JSON.stringify(value))
}
initListener() {
this.ngZone.runOutsideAngular(() => {
document.body.addEventListener('click', () => this.reset());
});
}
initInterval() {
this.ngZone.runOutsideAngular(() => {
setInterval(() => {
this.check();
}, CHECK_INTERVALL);
})
}
reset() {
this.lastAction(Date.now());
}
check() {
const now = Date.now();
const timeleft = parseInt(this.getlastAction()) + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
const diff = timeleft - now;
const isTimeout = diff < 0;
this.isLoggedIn$.subscribe(event => this.islogin = event);
this.ngZone.run(() => {
if (isTimeout && this.islogin) {
this.auth.logout();
this.router.navigate(['/admin/login']);
}
});
}
}发布于 2019-08-31 23:51:34
您正在使用localStorage来管理登录状态。当您关闭页面时,会话仍然存在,但超时代码停止运行。您可以切换到sessionStorage,它会将登录会话仅绑定到该选项卡。然而,这确实意味着,如果用户使用安全链接打开另一个选项卡,则必须登录。
如果您希望继续使用localStorage管理登录,另一种选择是在选项卡或浏览器关闭时触发注销。有关详细信息,请参阅How can we detect when user closes browser?。
https://stackoverflow.com/questions/57219328
复制相似问题