Skip to content

Instantly share code, notes, and snippets.

@Bidthedog
Last active July 25, 2018 11:00
Show Gist options
  • Save Bidthedog/8285042fa5200108e7135b841e623b5d to your computer and use it in GitHub Desktop.
Save Bidthedog/8285042fa5200108e7135b841e623b5d to your computer and use it in GitHub Desktop.
Angular 6 + RxJs 6 Refresh Token Interceptor - final retry cancels itself?
@Injectable()
export class HandleUnauthorisedRequestInterceptor implements HttpInterceptor {
constructor(
private securityService: SecurityService
) { }
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('intercepting ' + req.method + ' to ' + req.url);
// Ignore all security controller requests as they're all dealt with separately
if (req.url.indexOf('/security/') > -1) {
return next.handle(req);
}
// Handle 401 responses from all other responses - attempt to refresh token
// quietly. If refresh fails, log out and redirect
return next.handle(req)
.pipe(
retryWhen(error$ => {
return error$
.pipe(
flatMap((error: HttpErrorResponse) => {
if (error.status === 401) {
console.log('401 received - attempting refresh');
return from(this.securityService
.refreshAndHandle();
}
console.log('throwing...');
return Observable.throw({ error: 'No retries configured...' });
}),
take(1)
);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment