简体   繁体   English

如何在令牌在 angular 中过期时重定向到注销?

[英]How to redirect to logout when token expired in angular?

I have a angular 13 application.我有一个 angular 13 申请。 There I use JWT token for authentication purposes.在那里我使用 JWT 令牌进行身份验证。 Everything works fine.一切正常。 but the token expiration time I have given to the JWT token is 1 hour.但是我给 JWT 令牌的令牌到期时间是 1 小时。 I want to log the user out from the front end application once the token expired on the server-side.一旦令牌在服务器端过期,我想将用户从前端应用程序中注销。

I did this but it seems there is a problem and it didn't work for me:我这样做了,但似乎有问题并且对我不起作用:

export class authInterceptor implements HttpInterceptor {

  constructor(private userService: UserService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.userService.isAuthentificated()) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.userService.getToken()}`
        }
      });
    }
    return next.handle(request).pipe(
      tap(event => {
      }, error => {
        this.onSubscribeError(error);
      })
    );
  }

  private onSubscribeError(error: any): void {
    if (error.status === 401 || error.status === 403) {
      this.userService.logout();
    }
  }
}

can anyone tell me what I did wrong and help me correct it?谁能告诉我我做错了什么并帮我改正?

The link provided by E. Maggini is fine, technically, but the accepted answer for it, at least, is only relevant for letting the server decide if it's expired or not. E. Maggini 提供的链接在技术上很好,但接受的答案至少只与让服务器决定它是否过期有关。

If you're not making calls to the server and getting your 401, your UI stays logged in until you do.如果您没有调用服务器并收到 401,您的 UI 将保持登录状态,直到您这样做。

You need a mix of the two;你需要两者的结合; one added to your interceptor to check for your 401 and log you out (to be sure) and the app itself checking the token.一个添加到您的拦截器以检查您的 401 并将您注销(当然)并且应用程序本身检查令牌。

Simplest is to just have an interval on the go checking for your token's expiry.最简单的是在 go 上设置一个时间间隔来检查您的令牌是否过期。

Assuming you have some kind of singleton AuthService with basic login/logout handling...假设您有某种具有基本登录/注销处理功能的 singleton AuthService ...

@Injectable()
export class AuthService {
    private jwt: string;
    private expiryTimer: any;

    public login(jwt: string): void {
        this.jwt = jwt;
        this.expiryTimer = setInterval(() => { this.checkExpiry(); }, 60000);
        this.router.navigate(['...']);
    }

    public logout(): void {
        this.jwt = undefined;
        if (this.expiryTimer) clearInterval(this.expiryTimer);
        this.router.navigate(['...']);
    }

    private checkExpiry(): void {
        if (this.jwtService.hasExpired(this.jwt)) this.logout();
    }
}

Assuming you have some jwt service or method or whatnot to check the expiry...假设您有一些 jwt 服务或方法或诸如此类的东西来检查到期...

It'll look more complicated than that as, presumably, you'd actually be storing the token somewhere (local storage?) so that page refreshes are handled, etc. etc.它看起来会比这更复杂,因为您可能实际上将令牌存储在某个地方(本地存储?)以便处理页面刷新等。

But the basics are there - don't overthink it, it's as simple as just checking the token every x (1m good enough?) and if it's expired, logout...但基础知识就在那里——不要想太多,它就像每隔 x(1 米足够好?)检查一次令牌一样简单,如果它已过期,请注销……

Your modified interceptor will use the same thing;您修改后的拦截器将使用相同的东西; get a 401?得到一个 401? this.authService.logout(); . . Done.完毕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM