2

我正在使用可以激活防护和带有 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 属性并将人员导航到登录页面。该登录页面重定向没有发生。

如果我在时间过去并且令牌过期后回到页面,那么,我不应该能够在角度页面之间导航,但由于某种原因,我

任何帮助表示赞赏,谢谢!

4

1 回答 1

1

使用返回 true 的 CanActivate 允许用户进入路由路径,返回 false 的导航被取消。签出此链接

一个类可以实现的接口,作为决定是否可以激活路由的守卫。如果所有守卫都返回 true,则导航将继续。如果任何守卫返回 false,导航将被取消。如果任何守卫返回一个 UrlTree,当前导航将被取消,新的导航将被踢到从守卫返回的 UrlTree。

您可能期望注销功能从那里接管,但它可能无法按您预期的那样工作。看看这篇关于做什么的文章:链接

另外,请检查您的代码,它可能需要您的评论中提到的“/”。

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;
    }
  }
}
于 2020-01-17T22:33:18.273 回答