我正在使用一个可以激活的守护程序和一个带有JWT的Node服务器。正常运行期间的路由运作良好。但是,当令牌过期并且浏览器中仍存在该页面时,尽管没有API数据存在,但我仍可以在angular应用中单击。我已经检查了几次设置,看起来不错,但是由于某种原因,当令牌枯萎不存在或已过期时,它不会重定向到登录。
----- AUTH GUARD服务
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属性,并导航人员到登录页面。该登录页面重定向没有发生。
如果我在时间过去之后返回页面,并且令牌已过期,那么我就不能在有角度的页面之间导航,但是出于某些原因,我是
感谢您的任何帮助,谢谢!
使用CanActivate并返回true,将使用户进入路由路径,取消返回错误的导航。签出此link
类可以实现的接口,以决定是否可以激活路由。如果所有防护措施都返回true,则导航将继续。如果任何防护返回假,导航将被取消。如果任何防护程序返回了UrlTree,则当前导航将被取消,并且新的导航操作将启动到从防护程序返回的UrlTree。
您可能希望注销功能从那里接管,但可能无法按预期工作。签出有关如何做的写法:link
也请检查您的代码,如注释中所述,它可能需要一个'/'。
this._router.navigate(["/login"]);
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn) {
// redirect to some view explaining what happened
this.router.navigateByUrl('/notauthorized');
return false;
} else {
return true;
}
}
}