4
votes

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...

2
Hi Vipin, Did you get any way to get the refresh token using adal-angular5.V.S

2 Answers

0
votes

Please try the following and see if it works,

     import { Injectable } from '@angular/core';
     import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } 
     from '@angular/common/http';
     import { Observable } from 'rxjs/Observable';
     import { Adal5Service,Adal5HTTPService } 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, private adal5HttpService: Adal5HTTPService) { }

       intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
       {
          this.loaderService.display(true);
          let headers = new HttpHeaders();
          headers = headers
                   .set('Content-Type', 'application/json')
                   .set('Authorization', 'Bearer ${this.adalService.userInfo.token}');
          let authReq=this.adal5HttpService.get(url, headers )

         return next.handle(authReq).finally(() => this.loaderService.display(false));
    }
0
votes

I was also facing the same issue with angular adal , token is getting expired in one hour , I tried RenewToken function of adal library , it was generating a new token. After you call RenewToken function you need to call acquireToken method as well to update the token in localstorage.