如何检查身份验证是否仍然有效并在之后重定向?

How can I check if the authentication is still valid and redirect after?

如标题所说。我使用对 API 的请求来检查身份验证。如果请求 returns false,我想注销用户。但是,如果我与守卫一起执行此操作,则它不起作用,因为它 运行 是同步的,我无法等待每次转到另一个页面时显示该页面的请求。

示例:

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    this.authService.checkAuth(); // Sends request to backend for auth validation
    return this.authService.getIsAuthenticated(); // Shows/doesn't show page before validation
  }

如果我 运行 它是异步的,它会在每次显示页面之前等待响应。我希望它在请求期间显示页面,但如果请求 returns false,我想注销 ie this.authService.logout().

我可以不把它放在每个页面的 IonicViewDidLoad 中实现吗?

场景:

A user is logged in on two devices. The user unlinks one of the devices. So during the session, the other device needs to be logged out.

Possibly immediately. But I suspect this would require an interval to continueously check if the device is still logged in. Therefore it would suffice to do this on change of a page (like in the guard).

我使用 jwt 令牌作为授权句柄。 有一部分代码(拦截器)我检查用户是否已通过身份验证:

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any> | any> {

    return next.handle(this.addTokenToRequest(request, this.authService.getToken()))
      .pipe(
        catchError(err => {
        if (err.status === 0 || err.status === 401) {
            // if server return 401 Unauthorized
            this.authService.logout();
            location.reload(true);
        } else if (err.status === 302) {
          this.router.navigate(['/pages/technical-works']);
        } else {
              return throwError(err.error);
            }
          }));

      private addTokenToRequest(request: HttpRequest<any>, token: string): HttpRequest<any> {
           return request.clone({ setHeaders: { Authorization: `Bearer ${token}` } 
                               });
      }
}

所以如果服务器 return 未经授权的错误然后我在客户端注销。

我的解决方案的问题是我的身份验证适用于行为主体。出于这个原因,当我在 canActivate 中更改它时,它并没有像我想要的那样工作。但是我设法通过检查授权是否仍然有效来解决这个问题(结合@Roma Ruzich 的拦截器解决方案)。如果没有,请注销。

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.authService.getAuthStatus().subscribe((data: any) => {
      if (!data.deviceRegistered) {
        this.authService.logout();
      }
    });
    return this.authService.getIsAuthenticated();
  }