Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Created July 26, 2020 02:43
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 changhuixu/0149b1a9c408a89d2060cb4543803554 to your computer and use it in GitHub Desktop.
Save changhuixu/0149b1a9c408a89d2060cb4543803554 to your computer and use it in GitHub Desktop.
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
// add JWT auth header if a user is logged in for API requests
const accessToken = localStorage.getItem('access_token');
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (accessToken && isApiUrl) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${accessToken}` },
});
}
return next.handle(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment