0

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.

kishan
  • 189
  • 1
  • 4
  • 14

3 Answers3

0

You can set the AcessTokenLifetime to one day, if your issue is that it is timing out too soon. https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes

Marilee Turscak - MSFT
  • 7,367
  • 3
  • 18
  • 28
0

You have to call this.adalService.acquireToken method for all the http requests (get/post/update/delete). Create an interceptor/http wrapper class and intercept each http request, then call the this.adalService.acquireToken (returns you the current valid token always) and set the returned token to the Authorization header of each http request. You have to set a configuration of "expireOffsetSeconds": 1200 (means the new token will be generated 20 minutes before expiration. ie, every 40th minute a new token will get generated). The default value of expireOffsetSeconds is 120 (2 minutes), which should be increased to some higher value to avoid token refresh method returning null value. The configuration worked for me is 1200.

Refer the below link to see how to create an http Wrapper class to intercept every request and follow the steps too, https://www.npmjs.com/package/adal-angular5

Harun
  • 5,109
  • 4
  • 38
  • 60
0

Your code works fine as I took the reference from the same. The only problem I see in your code is, setinterval timing! ADAL's acquiretoken method uses either expireOffsetSeconds or the default offset value i.e. 5 mins to calculate the renewal interval. Which means, acquiretoken method will check if the token expiry is within the offset interval from the expiry or not. If it is not, then it will simply return the existing token because it is still valid. Only within that offset interval (which is by default- 5 min before the expiry), ADAL will be able to generate the renewal token using acquiretoken method. If you call the method before that, it will return cached token which is currently active, and if you call it after expiry, it will error out with the message "token renewal failed.". So adjust your settimeout in such a way that it falls into the "(expiry - offset)" window.