1
votes

well, I try make a login with refresh token but when the access token expire, dont refresh the token. I used djangorestframework-simplejwt for implementation jwt and angular 9 with rxjs. when try refresh the backend return something like

{ access: "asdsadlsadlsakdslañdksañldsakdsa"
}

but it is not compatible with rxjs

refreshAccessToken() {
    return this.http.post<any>(something http )this.getRefreshToken() }, this.httpOptions).pipe(
        map(token => {
            console.log(token)
            this.setNewAccessToken(token['access'])        
         })
       )        
}
public setNewAccessToken(token:string){
    localStorage.setItem("access", token);
}

and here the error that generates. core.js:6189 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

I am newbie with rxjs, so I so sorry if my ask is stupid.

2

2 Answers

0
votes

I don't think the example code is actually valid code but I see a classic mistake. You forgot to subscribe after the pipe. E.g. pipe(operators...).subscribe(token => {... do stuff };

0
votes

I tested only this code snippet but the mistake was not testing it in your implementation and after read more about rxjs, I understand when shall to use subcribe . T. van den Berg was right sometimes not to used subscribe generate mistakes in the result. In my particular case, subcribe is not used.

export class RefreshTokenService implements HttpInterceptor{
  private refrescarTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  private ruta_refrescar_token = "http://127.0.0.1:8000/api/token/refresh/";

  constructor(public loginService:LoginService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.loginService.get_token()) {
      request = this.addToken(request, this.loginService.get_token());
      this.refrescarTokenSubject.next(null);
    }

    return next.handle(request).pipe(catchError(error => {
      let refreshToken = localStorage.getItem('refresh')
      if (error.status === 401 && refreshToken !== null && error.url!==this.ruta_refrescar_token) {
        return this.manejarError401(request, next)
        //this.loginService.refreshAccessToken()
      } else {
        return throwError(error);
      }
    }));
  }
  
  private manejarError401(request: HttpRequest<any>, next: HttpHandler){
    this.refrescarTokenSubject.next(null)

    return this.loginService.refreshAccessToken().pipe(
      switchMap((token: any) => {
        console.log(token['access'])
        this.refrescarTokenSubject.next(token)
        return next.handle(this.addToken(request,this.loginService.get_token()))
      })
    )
  }

  private addToken(request: HttpRequest<any>, token: string) {
    return request.clone({
      setHeaders: {
        'Authorization': `Bearer ${token}`
      }
    });
  }
}