Refresh token (JWT) in interceptor Angular 6

…衆ロ難τιáo~ 提交于 2019-12-05 16:00:49

In your example you never subscribe to your refreshTokens().pipe() code. Without a subscription, the observable won't execute.

req = this.auth.refreshTokens().pipe(
      switchMap(() => req.clone({
            setHeaders: {
              Authorization: `Bearer ${this.auth.getToken()}`
            }
          }))
      )

This will first call refreshToken and run the tap there, then emit request with the new this.auth.getToken(), note that accToken still have old value as the code is not rerun.

You have to do something like that:

const firstReq= cloneAndAddHeaders(req);

return next.handle(firstReq).pipe(
   catchError(
      err => {
         if (err instanceof HttpErrorResponse) {
            if (err.status === 401 || err.status === 403) {
               if (firstReq.url === '/api2/auth/refresh')) {
                  auth.setToken('');
                  auth.setRefreshToken('');
                  this.router.navigate(['/login']);
               }
               else {
                  return this.auth.refreshTokens().pipe(
                     mergeMap(() => {
                        const secondReq = cloneAndAddHeaders(req);
                        return next.handle(secondReq);
                     })
                  );
               }
            }
            return throwError(err.message || 'Server error');
         }
      }
    )
 );

The implementation of cloneAndAddHeaders is obvious.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!