在Angular 4中处理来自Api的过期令牌

Jos*_*eph 10 token access-token angular-http angular

我需要帮助处理我的角度应用程序中的过期令牌.我的api有过期的时间但我的问题是当我忘记退出我的角度应用程序,一段时间后,我仍然可以访问主页但没有数据.我能做些什么吗?是否有可以处理此问题的库?或者有什么我可以安装?更好,如果我没有安装任何东西.这是我的身份验证码?我可以添加任何可以处理过期的内容吗?如果过期,我将无法访问该主页.

auth.service.ts

 export class AuthService {
  private loggedIn = false;

  constructor(private httpClient: HttpClient) {
  }

  signinUser(email: string, password: string) {  
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json');

    return this.httpClient
    .post(
      'http://sample.com/login', 
       JSON.stringify({ email, password }), 
       { headers: headers }
    )
    .map(
        (response: any) => {
          localStorage.setItem('auth_token', response.token);
          this.loggedIn = true;
          return response;
        });
   }

    isLoggedIn() {
      if (localStorage.getItem('auth_token')) {
        return this.loggedIn = true;
      }
    }

   logout() {
     localStorage.removeItem('auth_token');
     this.loggedIn = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

authguard.ts

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {

    if (this.authService.isLoggedIn()) {
      // logged in so return true
      return true;
    }

    else {
      // not logged in so redirect to login page with the return url
      this.router.navigate(['signin'])
      return false;
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

Kun*_*vič 7

我认为您可以使用两种解决方案。

当浏览器关闭时,第一个您可以调用注销功能:

  @HostListener('window:unload', ['$event'])
  handleUnload(event) {
    this.auth.logout();
  }
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/de/docs/Web/Events/unload

要么

 @HostListener('window:beforeunload', ['$event'])
      public handleBeforeUnload(event) {
        this.auth.logout();
      }
Run Code Online (Sandbox Code Playgroud)

https://developer.mozilla.org/de/docs/Web/Events/beforeunload

这样,当浏览器关闭时,您的this.auth.logout();将自动被调用。

其次,您可以安装像angular2-jwt这样的库,它可以帮助您检测令牌是否已过期

jwtHelper: JwtHelper = new JwtHelper();

useJwtHelper() {
  var token = localStorage.getItem('token');

  console.log(
    this.jwtHelper.decodeToken(token),
    this.jwtHelper.getTokenExpirationDate(token),
    this.jwtHelper.isTokenExpired(token)
  );
}
Run Code Online (Sandbox Code Playgroud)


Ami*_* Al 7

您可以使用http拦截器执行此操作.

intercept(req: HttpRequest<any>, next: HttpHandler) {
  if(!localStorage.getItem('token'))
    return next.handle(req);

  // set headers
  req = req.clone({
    setHeaders: {
      'token': localStorage.getItem('token')
    }
  })

  return next.handle(req).do((event: HttpEvent<any>) => {
    if(event instanceof HttpResponse){
      // if the token is valid
    }
  }, (err: any) => {
    // if the token has expired.
    if(err instanceof HttpErrorResponse){
      if(err.status === 401){
        // this is where you can do anything like navigating
        this.router.navigateByUrl('/login');
      }
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

这是完整的解决方案