angular - 令牌过期后如何自动退出系统?
问题描述
如果令牌过期而不刷新页面,是否可以以某种方式自动注销?也就是说,假设一个人在一个站点的页面上,关注它,然后关闭页面或简单地将其关闭,然后在一个小时后返回,并显示一条消息,指出由于令牌过期而退出。同时,要显示此消息,不需要刷新页面或在站点上执行任何操作。
import { Injectable } from "@angular/core";
import { AuthService } from "../services/auth.service";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { Router } from "@angular/router";
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(private auth: AuthService, private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.auth.isAuthenticated()) {
req = req.clone({
setHeaders: {
Authorization: this.auth.getToken()
}
});
}
return next.handle(req).pipe(catchError((error: HttpErrorResponse) => this.handleAuthError(error)));
}
private handleAuthError(error: HttpErrorResponse): Observable<any> {
if (error.status === 401) {
this.auth.signOut(), this.router.navigate(["/sign-in"]), {
queryParams: {
sessionFailed: true
}
};
}
return throwError(error);
}
}
解决方案
您可以为此使用路线守卫。这就是它的例子。
// src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
@Injectable()
export class AuthService {
constructor(public jwtHelper: JwtHelperService) {}
// ...
public isAuthenticated(): boolean {
const token = localStorage.getItem('token');
// Check whether the token is expired and return
// true or false
return !this.jwtHelper.isTokenExpired(token);
}
}
// src/app/auth/auth-guard.service.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
// src/app/app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import {
AuthGuardService as AuthGuard
} from './auth/auth-guard.service';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{ path: '**', redirectTo: '' }
];
推荐阅读
- apache-spark - Spark 在不同的列上多次加入相同的数据集
- node.js - 从 AWS Lambda 函数的 [ List ] DynamoDB 项目中查询
- c# - 在场景加载中保持不同的 PhotonView
- swift - 多个用户访问相同的用户默认数据 Swift
- python - 将 dict 理解转换为正常形式
- java - 将数据插入数据库时出现“org.springframework.beans.ConversionNotSupportedException”错误
- python - 表单字段输入的Python Django长度为1,即使它为空
- c# - Blazor:无法获取以对象为键的字典
- android - 如何获得具有相同价值的孩子的数量?
- html - 使用 golang 抓取网页内容