Mark Hill
Mark Hill

Reputation: 1839

Auth Token not refreshing after specific time using microsoft-adal-angular6 library

I have searched high and low for answers and have found nothing. I have an interceptor, seen below, that I am using to control the auth token on http requests. We have it set so that when the user is sending a request, if they are above the 15 minute mark, then we refresh and grab the new token. It is not doing this at all. However, if you come back in 10 mines and try it again, it will refresh the token.

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MsAdalAngular6Service } from 'microsoft-adal-angular6';
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';

@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor{
    constructor(private adalSvc: MsAdalAngular6Service) {

}

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const resource = this.adalSvc.GetResourceForEndpoint(request.url);
        if(!resource || !this.adalSvc.isAuthenticated) {
            return next.handle(request);
        }
        const currentEpoch = Math.round(Date.now() / 1000);
        const remainingTime = this.adalSvc.userInfo.profile.exp-currentEpoch;
        if(remainingTime >= 2700) { // set to 15 minutes to update silently while the user is working per Tristan's request
            const authorizedRequest = request.clone({
                headers: request.headers.set('Authorization', `Bearer ${this.adalSvc.getToken(request.url)}`),
            });
                return next.handle(authorizedRequest);
            }else if(remainingTime <= 0) {
                this.adalSvc.logout();
            }else { 
                this.adalSvc.RenewToken(request.url);
                return this.adalSvc.acquireToken(request.url).pipe(
                    mergeMap((token: string) => {
                        const authorizedRequest = request.clone({
                            headers: request.headers.set('Authorization', `Bearer ${token}`),
                        });
                        return next.handle(authorizedRequest);
                    })
                );
        }
    }
}

Upvotes: 2

Views: 298

Answers (1)

WorksLikeACharm
WorksLikeACharm

Reputation: 414

The angular wrapper for Msal has an interceptor implemented that does this for you, so

  • a) you could switch library (takes some time, i know)
  • b) you could inspect the code there. The class is called MsalInterceptor.

Here you can find the angular wrapper of that library: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/README.md

Upvotes: 1

Related Questions