在 Angular 4 中处理来自 Api 的过期令牌 [英] Handling Expired Token From Api in Angular 4

查看:22
本文介绍了在 Angular 4 中处理来自 Api 的过期令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助来处理我的 Angular 应用程序中的过期令牌.我的 api 有过期时间,但我的问题是当我忘记退出我的 angular 应用程序时,一段时间后,我仍然可以访问主页但没有数据.我能做些什么吗?有没有可以处理这个的库?或者有什么我可以安装的吗?更好,如果我什么都不会安装.下面是我的验证码?我可以添加任何可以处理过期的东西吗,如果它过期,我将无法访问主页.

<块引用>

auth.service.ts

 导出类 AuthService {私人登录=假;构造函数(私有 httpClient:HttpClient){}登录用户(电子邮件:字符串,密码:字符串){const 标头 = 新的 HttpHeaders().set('内容类型', '应用程序/json');返回 this.httpClient.邮政('http://sample.com/login',JSON.stringify({ email, password }),{ 标题:标题}).地图((回复:任何)=>{localStorage.setItem('auth_token', response.token);this.loggedIn = true;返回响应;});}isLoggedIn() {如果(localStorage.getItem('auth_token')){返回 this.loggedIn = true;}}登出() {localStorage.removeItem('auth_token');this.loggedIn = false;}}

<块引用>

authguard.ts

@Injectable()导出类 AuthGuard 实现 CanActivate {构造函数(私有路由器:路由器,私有 authService:AuthService){}canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot){如果 (this.authService.isLoggedIn()) {//已登录,所以返回真返回真;}别的 {//未登录,因此使用返回 url 重定向到登录页面this.router.navigate(['signin'])返回假;}}}

解决方案

我认为您可以尝试两种解决方案.

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

 @HostListener('window:unload', ['$event'])处理卸载(事件){this.auth.logout();}

https://developer.mozilla.org/de/docs/Web/事件/卸载

 @HostListener('window:beforeunload', ['$event'])公共 handleBeforeUnload(事件){this.auth.logout();}

https://developer.mozilla.org/de/docs/Web/事件/beforeunload

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

第二你可以安装像angular2-jwt这样的库帮助您检测是否已过期

jwtHelper: JwtHelper = new JwtHelper();useJwtHelper() {var token = localStorage.getItem('token');控制台日志(this.jwtHelper.decodeToken(token),this.jwtHelper.getTokenExpirationDate(token),this.jwtHelper.isTokenExpired(token));}

I need help in handling expired token in my angular application. My api has the expired time but my problem is when i forgot to log out of my angular application, after some time, i still can access the homepage but without data. Is there something i can do about this? Are there libraries that can handle this? or are there something i could install? Better, if i nothing will be installed. Here's my authentication code below? Can i add anything that can handle expiration and I won't be able to access the homepage if it expires.

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;
    }
}

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;
      }
  }
}

解决方案

I think there is two solution you can play with.

The first one you can just call you logout function when browser getting closed like:

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

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

OR

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

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

This way alway when browser getting closed your this.auth.logout(); will be called automatically.

Second you can install library like angular2-jwt it can help you to detect if token has expired

jwtHelper: JwtHelper = new JwtHelper();

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

  console.log(
    this.jwtHelper.decodeToken(token),
    this.jwtHelper.getTokenExpirationDate(token),
    this.jwtHelper.isTokenExpired(token)
  );
}

这篇关于在 Angular 4 中处理来自 Api 的过期令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆