I am using adal-angular4 (https://www.npmjs.com/package/adal-angular4) for Azure AD Authentication in my Angular 7 application. adal-angular provides an Access Token whose validity is 1 hr. I need to implement Refresh Token functionality so that I acquire new Token using acquireToken() method of AdalService. I have added required logic to get the Refresh Token using acquireToken() method. I even get the Refreshed Token but still my session gets expired after Token is expired. I have written logic which runs every 5 minutes. The logic checks the difference of Epoch time of Token expiration and current time. If this difference in time is less that 5 minutes then I call AdalService acquireToken() method which returns me new Token. However, still the Token expires after 1 hour and my session Time outs.
Below is my code details:- app.component.ts
ngOnInit() {
// Acquire Refresh Token
if (this.adalService.userInfo.authenticated) {
setInterval(() => {
this.authService.refreshToken(); }, 300000); // 300000 ms = 5 minutes
}
}
auth.service.ts
refreshToken(): boolean {
const token = this.adalService.userInfo.token;
const decodedToken = jwt_decode(token);
const tokenExpiresIn = decodedToken['exp'];
const currentEpochTime = Math.floor(new Date().getTime() / 1000.0);
const epochDiffInMins = Math.floor((tokenExpiresIn - currentEpochTime) / 60); // Epoch time difference in minutes
if (epochDiffInMins < 5) {
this.adalService.acquireToken(environment.adalConfig.clientId).toPromise().then((data) => {
this.processLoginRequest(this.adalService.userInfo);
return true;
},
(error) => {
return false;
});
}
return false;
}
processLoginRequest(response: any) {
if (response) {
localStorage.setItem(Constants.localStorageKeys.isLoggedIn, 'true');
localStorage.setItem(Constants.localStorageKeys.apiToken, JSON.stringify(response.token));
localStorage.setItem(Constants.localStorageKeys.userId, response.userName);
location.reload();
}
}
auth-gaurd.service.ts
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(
private router: Router,
private logger: LoggerService,
private authService: AuthService,
private adalService: AdalService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const url: string = state.url;
if (!this.adalService.userInfo.authenticated) {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
return true;
}
}
Any Quick help will be appreciated. Thanks in Advance.