Created
November 22, 2020 10:20
-
-
Save sunilkumarmedium/35ab325fd0ed4a770fc600ab92f1c509 to your computer and use it in GitHub Desktop.
jwt.inteceptor.ts
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 { 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