I'm trying to intercept any httpError 401 and resending the Request again with an updated Auth Token. Similair to the following Problem: Angular 4 Interceptor retry requests after token refresh
The Main struggles I have are
- understanding how the http sending works in the answer without having any subscribe anywhere. If I omitted the subsrcribe the token refresh request would never actually be sent. That's why I added a subscribe in the
refreshToken()
method - Finding out what methods I have to pipe onto the Observable to resend the request
I tried to pipe serval methods individually onto the observable in the intercept()
but none of them ever got called.
I tried (each method without the others) :
observable.pipe(
tap((data) => {
console.log(data)
return next.handle(this.addAuthHeader(request))
})
)
observable.pipe(
switchMap((data) => {
console.log(data)
return next.handle(this.addAuthHeader(request))
})
)
observable.pipe(
mergeMap((data) => {
console.log(data)
return next.handle(this.addAuthHeader(request))
})
)
I built a httpInterceptor for this:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthenticationService) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
request = this.addAuthHeader(request)
return next.handle(request).pipe(
catchError((error: any) => {
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
let observable = this.auth.refreshToken();
}
}
})
);
}
That calls the following method to refresh the Authentication Token
refreshToken(): Observable<any> {
let observable = this.http.post<KeyCloakToken>(`${this.authUrl}/auth/refresh`, {this.refreshToken})
.pipe(
tap(data => console.log("tap in refreshToken",data) )
);
observable.subscribe((data) => this.saveCookie(data))
return observable;
}
What works so far is the Authentication Backend Server gets called and the refreshToken is stored into the cookie. However the HttpRequest that was sent that got the 401 Error is never resent and therefor the Website kinda gets stuck in a reload stage until you refresh manually.