Skip to content

Instantly share code, notes, and snippets.

@sunilkumarmedium
Created November 22, 2020 10:20
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 sunilkumarmedium/35ab325fd0ed4a770fc600ab92f1c509 to your computer and use it in GitHub Desktop.
Save sunilkumarmedium/35ab325fd0ed4a770fc600ab92f1c509 to your computer and use it in GitHub Desktop.
jwt.inteceptor.ts
import { AuthenticationService } from './../_services/authentication/authentication.service';
import { environment } from './../../environments/environment';
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private authenticationService: AuthenticationService,
) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const user = this.authenticationService.userValue;
const isLoggedIn = user && user.token;
const userToken = user?.token;
const isApiUrl = request.url.startsWith(environment.baseWebApiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${userToken}`
}
});
}
return next.handle(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment