Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikecabana/6409d5c8509515bc2b1ecb898d3bef86 to your computer and use it in GitHub Desktop.
Save mikecabana/6409d5c8509515bc2b1ecb898d3bef86 to your computer and use it in GitHub Desktop.
Authorization Token Interceptor Service - Async HTTP Interceptors | Angular 6.x | rxjs 6.x
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { User } from 'oidc-client';
import { AuthService } from './oidc-auth.service.ts';
@Injectable({
providedIn: 'root'
})
export class TokenInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.getUser()
.pipe(
mergeMap((user: User) => {
// OPTIONAL - wrapper to do nothing if pre-flight request
if (request.method !== 'OPTIONS') {
if (user) {
// clone and modify the request
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${user.access_token}`
}
});
}
return next.handle(request)
.pipe(
tap(
() => {
// OPTIONAL - do something on success
},
(err: any) => {
// handle request errors
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// TODO - your choice of UserManager function to renew authorization i.e. singinSilent or signinRedirect.
}
}
}));
} else {
return next.handle(request);
}
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment