Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptor with firebase authentication

I am having issues with my Angular 6 Interceptor. I have migrated the code from Angular 5.x to 6.0. and rxjs 5.x to 6.x. When I try to create a new user account, the request seems to be called twice. I know this because I log the error to the console. I have noticed that I get this duplication when I try to get the Id token from firebase auth, See code snippet below.

intercept (request: HttpRequest<any>, next: HttpHandler): observable<HttpEvent<any>> {
return this.auth.getIdToken().pipe(
    mergeMap((token: any) => {
      if (token) {
        request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
      }

      return next.handle(request).pipe(
        tap((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {

          }
        }, (err: any) => {
          if (err instanceof HttpErrorResponse) {
            if ((err.status === 401) || (err.status === 403)) {
             this.router.navigate([WellknownRoutesConstants.SIGN_IN], { queryParams: { returnUrl: this.router.routerState.snapshot.url }});
            }
          }
        })
    );

  }));

}

getIdToken (): Observable<any> {
  return ngFireAuth.authState.pipe(
    tap((user) => {
      if (user) {
        return observableOf(user.getIdToken());
      } else {
        return observableOf;
      }
    }),
    catchError(observableOf)
  );
}
like image 919
Tionne Lee Avatar asked Jun 27 '18 02:06

Tionne Lee


2 Answers

Grant's answer is good, but there is a problem.

If the user logs out, the auth.idToken Observable emits a value because the token value changes to null. The request object remains unchanged (but still initialised), and so the HTTP request is repeated.

I used take(1) to take only the first value emitted by the auth.idToken Observable. I also changed to switchMap (see take):

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

   return this.auth.idToken.pipe(
      take(1), // <-------------- Only emit the first value!

      switchMap((token: any) => {
        if (token) {
          request = request.clone({
            setHeaders: { Authorization: `Bearer ${token}` }
          });
        }
        return next.handle(request);
      })

    );
}
like image 94
Jack Avatar answered Sep 19 '22 11:09

Jack


This works for me since upgrading to Angular 6 / RxJS 6. Here's my interceptor:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

@Injectable()

export class TokenInterceptor implements HttpInterceptor {

  constructor(
    private auth: AngularFireAuth
  ) {
    console.log('token interceptor constructor');
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.idToken.pipe(
      mergeMap((token: any) => {
        console.log(token);
        if (token) {
          request = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
        }

        return next.handle(request);

    }));
  }
}
like image 31
Grant Avatar answered Sep 21 '22 11:09

Grant