Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

139
Visualizações
Angular 10: repeat the same http request after obtaining the refresh token

I am trying to achieve the following in my HTTP calls

  1. If an API request returns 401 then call the refresh token endpoint to get the token.
  2. Retry the same HTTP call with the updated token

Here is the relevant code

// this method invoke when the HTTP interceptor returns 401 status code

handle401(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.refreshTokenInProgress) {
      this.refreshTokenInProgress = true;
      this.refreshTokenSubject.next(null);
      return this.getToken((data: any) => {
        this.refreshTokenInProgress = false;
        this.refreshTokenSubject.next(data);
        request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${data}`) });
        return next.handle(request);
      })
    } else {
      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(1),
        switchMap((accessToken) => {
          request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
          return next.handle(request);
        })
      );
    }
  }

Obtain the refresh token

getToken(cb: any) {
    let poolData = {
      UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
      ClientId: environment.cognitoAppClientId // Your client id here
    };
    let userPool = new CognitoUserPool(poolData);
    let cognitoUser = userPool.getCurrentUser();
    cognitoUser?.getSession((err: any, session: any) => {
      const refresh_token = session.getRefreshToken();
      cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
        
        const userToken = localStorage.getItem('token');
        cb(userToken);
      });
    })
  }

While executing I am getting the new token from the getToken method, but the retry of the same HTTP call is not happening.

The execution of HTTP request stops after obtaining the refresh token from the getToken method.

Can somebody please help on this issue

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Assuming you want to get userToken from getToken(). getToken() should return something, right now it's not returning anything. If some methods like getSession or refreshSession are async methods then those should be waited too.

 async handle401(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.refreshTokenInProgress) {
      this.refreshTokenInProgress = true;
      this.refreshTokenSubject.next(null);
      const token = await this.getToken(); // put "cb" param here, wait for returned token, then continiue
        this.refreshTokenInProgress = false;
        this.refreshTokenSubject.next(token);
        request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${token}`) });
        return next.handle(request);

    } else {
      return this.refreshTokenSubject.pipe(
        filter(token => token != null),
        take(1),
        switchMap((accessToken) => {
          request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
          return next.handle(request);
        })
      );
    }
  }

getToken(cb: any) {
    let poolData = {
      UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
      ClientId: environment.cognitoAppClientId // Your client id here
    };
    let userPool = new CognitoUserPool(poolData);
    let cognitoUser = userPool.getCurrentUser();
    cognitoUser?.getSession((err: any, session: any) => {
      const refresh_token = session.getRefreshToken();
      cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
        
        const userToken = localStorage.getItem('token');
        cb(userToken);
        return userToken;
      });
    })
  }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda