Angular 6:所有路线上的守卫都不起作用

Ofi*_*son 2 authentication parameters routes typescript angular

我试图通过只允许某些 ID 访问来确保前端的安全。我希望如果有人尝试输入除 之外的任何路线/login/:id,如果他尚未登录,他会收到页面未找到的信息,但它不起作用。

这些是我的路由表和防护:

编辑: 我解决了问题并更新了代码:

应用程序路由.module.ts

// Routing array - set routes to each html page
const appRoutes: Routes = [{
    path: 'login/:id',
    canActivate: [AuthGuard],
    children: []
  },
  {
    path: '',
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [{
        path: '',
        redirectTo: '/courses',
        pathMatch: 'full'
      },
      {
        path: 'courses',
        component: CourseListComponent,
        pathMatch: 'full'
      },
      {
        path: 'courses/:courseId',
        component: CourseDetailComponent,
        pathMatch: 'full'
      },
      {
        path: 'courses/:courseId/unit/:unitId',
        component: CoursePlayComponent,
        children: [{
            path: '',
            component: CourseListComponent
          },
          {
            path: 'lesson/:lessonId',
            component: CourseLessonComponent,
            data: {
              type: 'lesson'
            }
          },
          {
            path: 'quiz/:quizId',
            component: CourseQuizComponent,
            data: {
              type: 'quiz'
            }
          }
        ]
      }
    ]
  },
  {
    path: '**',
    component: PageNotFoundComponent,
    pathMatch: 'full'
  }
];
Run Code Online (Sandbox Code Playgroud)

auth.guard.ts

canActivate(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
  Observable<boolean> | Promise<boolean> {
    // save the id from route snapshot
    const id = +route.params.id;

    // if you try to logging with id
    if (id) {
      this.authUserService.login(id);

      // if there was error - return false
      if (this.authUserService.errorMessage) {
        this.router.navigate(["/page_not_found"]);
        return false;
      }

      // there wasn't any errors - redirectTo courses and
      // continue
      else {
        this.router.navigate(["courses"]);
        return true;
      }
    }

    // if you already logged and just navigate between pages
    else if (this.authUserService.isLoggedIn())
      return true;

    else {
      this.router.navigate(["/page_not_found"]);
      return false;
    }
  }

canActivateChild(route: ActivatedRouteSnapshot, state:
    RouterStateSnapshot): boolean |
  Observable<boolean> | Promise<boolean> {
    return this.canActivate(route, state);
  }
Run Code Online (Sandbox Code Playgroud)

auth-user.service.ts

export class AuthUserService implements OnDestroy {

  private user: IUser;
  public errorMessage: string;
  isLoginSubject = new BehaviorSubject<boolean>(this.hasToken());

  constructor(private userService: UserService) {}

  // store the session and call http get
  login(id: number) {
    this.userService.getUser(id).subscribe(
      user => {
        this.user = user;
        localStorage.setItem('user', JSON.stringify(this.user));

        localStorage.setItem('token', 'JWT');
        this.isLoginSubject.next(true);
      },
      error => this.errorMessage = <any>error
    );
  }

  // if we have token the user is loggedIn
  // @returns {boolean}
  private hasToken(): boolean {
    return !!localStorage.getItem('token');
  }

  // @returns {Observable<T>}
  isLoggedIn(): Observable<boolean> {
    return this.isLoginSubject.asObservable();
  }

  // clear sessions when closing the window
  logout() {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    this.isLoginSubject.next(false);
  }

  ngOnDestroy() {
    this.logout();
  }
Run Code Online (Sandbox Code Playgroud)

Ofi*_*son 5

所以我设法解决了这个问题。我添加到 Login/:id Children: [] 的路由中,并将 isLoggedIn 更改为 BehaviourSubject,以便令牌在刷新或在页面之间移动后不会更改,并且它有效。我更新了帖子中的代码,以便每个人都可以看到解决方案