I have an angular project(version 5.2), and using ADAL service(adal-angular5). After inactivity of 1 hour, user gets 401(unauthorized) from API response. To avoid this, i want to refresh token every time before calling API. I made an interceptor. Here is my code:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Adal5Service } from 'adal-angular5';
import { environment } from '../environments/environment';
import { LoaderService } from './services/loader.service';
@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
constructor(private adalService: Adal5Service, private loaderService: LoaderService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.display(true);
const jwt = this.adalService.userInfo.token;
const authReq = req.clone({
url: environment.apiUrl + req.url,
headers: req.headers
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer ' + jwt)
});
return next.handle(authReq).finally(() => this.loaderService.display(false));
}
}
Please suggest me the best way to refresh token...