Interceptor with firebase authentication
Solution 1:
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);
})
);
}
Solution 2:
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);
}));
}
}