Created
December 13, 2019 20:17
-
-
Save inorganik/9dcd1e101bba1dbbc6db520165df0a06 to your computer and use it in GitHub Desktop.
Example of an angular auth interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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