为Angular 2身份验证前端添加会话超时 [英] Adding Session Timeout for Angular 2 Authentication front-end
本文介绍了为Angular 2身份验证前端添加会话超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经按照以下教程[1]设置了我的应用程序的身份验证.现在,我需要通过为Angular 2前端添加会话超时来修改身份验证.会话应在20分钟后过期,然后再次要求用户登录.
I have follow the following tutorial[1] to setting up the authentication for my application. Now I need to modify the authentication by adding the session timeout for Angular 2 front-end. That is in 20 minutes after the session should expire and ask the user again to login.
如何为身份验证系统开发此扩展功能.
How could I develop this extended feature for my authentication system.
[1] http://jasonwatmore.com/post/2016/09/29/angular-2-user-registration-and-login-example-tutorial
推荐答案
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
import 'rxjs/add/Observable/timer';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/switch';
@Injectable()
export class AuthService {
private authState: AuthState;
private authManager: BehaviorSubject<AuthState>;
public authChange$: Observable<AuthState>;
constructor() {
this.authManager = new BehaviorSubject(AuthState.LOGGED_OUT);
this.authChange$ = this.authManager.asObservable();
this.authChange$
.filter((authState:AuthState) => authState === AuthState.LOGGED_IN)
.map( (authState:AuthState) => Observable.timer(SESSION_TIMEOUT))
.do( () =>
console.log('Logged In. Session Timout counting down from now'))
.switch()
.subscribe( () => {console.log('Timer ended: Logging out')
this.logout();
});
}
login() {
this.setAuthState(AuthState.LOGGED_IN);
}
logout() {
this.setAuthState(AuthState.LOGGED_OUT);
}
emitAuthState():void {
this.authManager.next(this.authState);
}
private setAuthState(newAuthState:AuthState):void {
console.log('AuthService: setAuthState: ',
AuthState[newAuthState.toString()]);
if (newAuthState != this.authState) {
this.authState = newAuthState;
this.emitAuthState();
}
}
export enum AuthState {
LOGGED_IN,
LOGGED_OUT
}
const SESSION_TIMEOUT = 5000;
这篇关于为Angular 2身份验证前端添加会话超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文