Last active
September 16, 2021 19:19
-
-
Save davestacey/252e5e2ab2c87b4e9d49769489758169 to your computer and use it in GitHub Desktop.
JWT 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 { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http'; | |
import { Observable } from 'rxjs'; | |
import { AuthenticationService } from '@/_services'; | |
@Injectable() | |
export class JwtInterceptor implements HttpInterceptor { | |
constructor(private authenticationService: AuthenticationService) {} | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
// add authorization header with jwt token if available | |
let currentUser = this.authenticationService.currentUserValue; | |
if (currentUser && currentUser.token) { | |
request = request.clone({ | |
setHeaders: { | |
Authorization: `Bearer ${currentUser.token}` | |
} | |
}); | |
} | |
return next.handle(request); | |
} | |
} |
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 { NgModule } from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
import { ReactiveFormsModule } from '@angular/forms'; | |
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; | |
// used to create fake backend | |
import { fakeBackendProvider } from './_helpers'; | |
import { appRoutingModule } from './app.routing'; | |
import { JwtInterceptor, ErrorInterceptor } from './_helpers'; | |
import { AppComponent } from './app.component'; | |
import { HomeComponent } from './home'; | |
import { LoginComponent } from './login'; | |
import { RegisterComponent } from './register'; | |
import { AlertComponent } from './_components'; | |
@NgModule({ | |
imports: [ | |
BrowserModule, | |
ReactiveFormsModule, | |
HttpClientModule, | |
appRoutingModule | |
], | |
declarations: [ | |
AppComponent, | |
HomeComponent, | |
LoginComponent, | |
RegisterComponent, | |
AlertComponent | |
], | |
providers: [ | |
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, | |
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, | |
// provider used to create fake backend | |
fakeBackendProvider | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment