AcquireTokenSilent not refreshing token | using MSAL & Angular 11

I am using MSAL with below version:

"@azure/msal-angular": "^2.0.3", "@azure/msal-browser": "^2.17.0",

Requirement > Every 10 minutes the token should get refreshed.

Implementation > I have added some code in my existing interceptor so that with each API call in/after an interval of 15 minutes It should refresh the token ..Code below:

      export class AuthorizationInterceptor implements HttpInterceptor {
  requesttoken: SilentRequest = {
    scopes: ['profile'],
    account: this.msalService.instance.getAllAccounts()[0]
  };
  constructor(private msalService: MsalService, public webUtilitiesService: WebUtilitiesService,) { }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const token = sessionStorage.getItem('AuthorizationToken');
    if (this.msalService.instance.getActiveAccount()) {
      this.msalService.acquireTokenSilent(this.requesttoken).subscribe(result => {
        sessionStorage.removeItem('AuthorizationToken');
        sessionStorage.setItem('AuthorizationToken', result.idToken);
        if (token != result.idToken) { // To check if the token has been refreshed or not
          console.log("token is updated at " + Date.now());
          alert("i have refreshed the token")
          //this.setSessionId();
        }
      })
    }
    if (!token) {
      return next.handle(request);
    }

    const req = request.clone({
      headers: request.headers.set('Authorization', `Bearer ${token}`),
    });
    return next.handle(req);
  }

Test case >1)Login to the app. A token is successfully generated on login which is then sent with every API call.2) Leave the system idle for 20 minutes. My expectation is that after 20 minutes if an API call is made , the new token should be generated and sent with the API call. But here the token is not generated.

If I continuously keep working on Application, it refreshes the token smoothly.

0 ответов

Другие вопросы по тегам