Search code examples
angularamazon-cognitoaws-amplify

How can i get/use accessToken in AuthInterceptor class in Angular 8


How can i get/use accessToken in AuthInterceptor class & adding it to every API (.NetCore) call. I've already implemented

 getAccessToken() {
    return Auth.currentSession().then(res => {
      return res.getAccessToken().getJwtToken();
    });
  }

in authService, But i can't seem to use this in intercept(req: HttpRequest, next: HttpHandler){} method. Any way around or flow changes i can implement.


Solution

  • First, convert your promise to an Observable into your AuthService.ts :

    import { from } from 'rxjs';
    import { switchMap } from 'rxjs/operators';
    
    ...
    
    getAccessToken(): Observable<string> {
      return from(Auth.currentSession()).pipe(
        switchMap(session => from(session.getAccessToken().getJwtToken())
      )
    };
    
    

    Then you can use it easily into your AuthHttpInterceptor :

    @Injectable()
    export class AuthHttpInterceptor implements HttpInterceptor {
      constructor(
        private authService: AuthService
      ) { }
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return this.authService.getAccessToken().pipe(
          switchMap(jwtToken => {
            // clone the request to add the new header.
            const authReq = req.clone({ 
              headers: req.headers.set('Authorization', `Bearer ${jwtToken}`) 
            });
            return next.handle(authReq);
          })
        );
      }
    }