I have a angular 4 application. There i use JWT token for authentication purposes. Everything works fine. but the token expiration time i have given to the JWT token is 1 hour.
You can use Http Interceptors. If any Unauthorized 401 response. Suppose you are sending a http request with token in header. your server side code check your token and finally find out, token is invalid/expire return 401 code and you can redirect the user to login page. and manually passing token and checking all http request authorized/unauthorized is very repeated work, this common task you can do by interceptors as delegate for http request. see the code samples you'll get your solution.
AppHttpInterceptor.ts
import { Injectable } from "@angular/core";
import {
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpErrorResponse,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Router } from '@angular/router'
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(private router: Router){
}
headers = new Headers({
'Content-Type': 'application/json',
'Token': localStorage.getItem("Token")
});
intercept(req: HttpRequest, next: HttpHandler): Observable> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const authReq = req.clone({ headers: req.headers.set("Token", localStorage.getItem("Token")) });
console.log("Sending request with new header now ...");
//send the newly created request
return next.handle(authReq)
.catch(err => {
// onError
console.log(err);
if (err instanceof HttpErrorResponse) {
console.log(err.status);
console.log(err.statusText);
if (err.status === 401) {
window.location.href = "/login";
}
}
return Observable.throw(err);
}) as any;
}
}
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClient } from "@angular/common/http";
import { FormsModule } from '@angular/forms';
import { ToasterModule, ToasterService } from "angular2-toaster";
import { BrowserAnimationsModule } from '@angular/platform-browser /animations';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {AppHttpInterceptor} from './Common/AuthInterceptor';
import { AppRoutes } from '../app/Common/Routes';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule, HttpModule,HttpClientModule, ReactiveFormsModule, FormsModule, BrowserAnimationsModule, RouterModule.forRoot(AppRoutes)
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppHttpInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private httpClient: HttpClient){
this.httpClient.get("https://jsonplaceholder.typicode.com/users").subscribe(
success => {
console.log("Successfully Completed");
console.log(success);
}
);
}
}