Skip to content

Instantly share code, notes, and snippets.

@inorganik
Created December 13, 2019 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inorganik/9dcd1e101bba1dbbc6db520165df0a06 to your computer and use it in GitHub Desktop.
Save inorganik/9dcd1e101bba1dbbc6db520165df0a06 to your computer and use it in GitHub Desktop.
Example of an angular auth interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthContextManagerService } from './some/where/authContextService.ts';
@Injectable()
export class AuthorizationInterceptor implements HttpInterceptor {
constructor(private authContextService: AuthContextManagerService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authContext = this.authContextService.getAuthContext();
const token = authContext && authContext.accessToken;
if (!token || !this.needAuthHeader(req)) {
return next.handle(req);
}
return next.handle(
req.clone({
setHeaders: { Authorization: token },
})
);
}
/**
* determine which requests should contain the Authorization token
*/
private needAuthHeader(req: HttpRequest<any>): boolean {
return req.url.startsWith('https://') || req.url.indexOf('localhost') > 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment