我正在使用可以激活防护和带有 JWT 的节点服务器。正常运行期间的路由运行良好。但是,当令牌过期并且页面仍然存在于浏览器中时,我可以在 Angular 应用程序中单击,尽管不存在 API 数据。我已经检查了几次我的设置,它看起来正确,但是,由于某种原因,当令牌不存在或过期时,它不会重定向到登录。
----- 身份验证服务
import { Injectable } from "@angular/core";
import { CanActivate } from "@angular/router";
import { AuthService } from "../auth/auth.service";
import { UserService } from "../user.service";
@Injectable({ providedIn: "root" })
export class AuthGuardService implements CanActivate {
constructor(public userService: UserService, public auth: AuthService) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.userService.logout();
return false;
}
return true;
}
}
----- 授权服务
import { Injectable } from "@angular/core";
import * as jwt_decode from "jwt-decode";
import { UserService } from "../user.service";
import { Router } from "@angular/router";
@Injectable({ providedIn: "root" })
export class AuthService {
constructor(public userService: UserService, private _router: Router) {}
///// Method to check if user is authenticated (normal employees / non-admin)
public isAuthenticated(): boolean {
// Get token from localstorage
const token = localStorage.getItem("token");
// Check to see if token exists, if not return false
if (!token) {
return false;
}
// Decode token and get expiration date
const decoded = jwt_decode(token);
const date = decoded.exp;
// check if expiration is less than current time, if so return true
if (date < Date.now()) {
this.userService.setCurrentUser(decoded);
return true;
} else {
return false;
}
}
}
----- 基本路线
{
path: "projects",
component: ProjectsComponent,
canActivate: [AuthGuardService]
},
----- 用户服务注销方法
// Logout (used in navbar and by auth service)
logout() {
localStorage.removeItem(this.TOKEN_KEY);
this.removeCurrentUser();
this._router.navigate(["login"]);
}
一切似乎都是正确的。用户从 API 获取令牌,进入本地存储。在每条路线上,都会读取令牌并检查日期,如果仍未过期,则返回 true,路线良好。如果令牌过期,那么我会调用用户服务和注销方法。该方法销毁令牌,删除 currentUser 属性并将人员导航到登录页面。该登录页面重定向没有发生。
如果我在时间过去并且令牌过期后回到页面,那么,我不应该能够在角度页面之间导航,但由于某种原因,我
任何帮助表示赞赏,谢谢!