question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

token renewal operation failed due to timeout MSAL

See original GitHub issue

Hi,

Library : “@azure/msal-angular”: “^1.0.0-beta.5” “msal”: “^1.2.2”

I have integrated MSAL library with my angular 8 application. Everything works fine except i keep getting an error token renewal operation failed due to timeout as soon as the token is expired. I was wondering how to fix this.

Below is the MSAL_config that i am using :

"auth": {
        
        "clientId": "xxxxx",
        "authority": "https://login.microsoftonline.com/xxx",
        "validateAuthority":"true",
        "postLogoutRedirectUri": "http://localhost:4200/",
        "navigateToLoginRequestUrl": true,
        "redirectUri":"http://localhost:4200/"
    },
    
    "scopes":["user.read", "openid", "profile"],
    "popUp": false,
    "unprotectedResources": ["https://www.microsoft.com/en-us/"],
    "protectedResourceMap":[["https://graph.microsoft.com/v1.0/me", ["user.read"]]],
    "system":{
        "loadFrameTimeout":10000
    },
    "cache": {
      "cacheLocation": "localStorage",
      "storeAuthStateInCookie":true

    }

I have created a new token interceptor which pull the token everytime a http request is amde. Below is the code, here i face issue when the token is expired and i get the error. Please help me to resolve this as it is affecting the project.

if (this.authService.getAccount()) {
 

                let token: string;
                return from(
                    this.authService.acquireTokenSilent(this.loginRequest)
                        .then((response: AuthResponse) => {
            
                            token = response.idToken.rawIdToken;
                            const authHeader = `Bearer ${token}`;
                            if (!request.headers.has('Cache-Control')) {
                                request = request.clone({ headers: request.headers.set('Cache-Control', 'no-cache' + '') });
                            }

                            if (!request.headers.has('Pragma')) {
                                request = request.clone({ headers: request.headers.set('Pragma', 'no-cache' + '') });
                            }

                            if (!request.headers.has('Expires')) {
                                request = request.clone({ headers: request.headers.set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT' + '') });
                            }
                            return request.clone({
                                setHeaders: {
                                    Authorization: authHeader,
                                }
                            });

                        })
                )
                    .pipe(
                        mergeMap(nextReq => next.handle(nextReq)),
                        tap(
                            event => { },
                            err => {
                                if (err) {
                                    var iframes = document.querySelectorAll('iframe');
                                    for (var i = 0; i < iframes.length; i++) {
                                        iframes[i].parentNode.removeChild(iframes[i]);
                                    }
                                    debugger
                                    
                                    this.authService.handleRedirectCallback((err: AuthError, response) => {
                                        debugger
                                        this.authService.loginRedirect();
                                        if (err) {

                                            console.error('Redirect Error: ', err.errorMessage);
                                            return;
                                        }
                                        debugger
                                        this.authService.loginRedirect();
                                        console.log('Redirect Success: ', response);
                                    });
                                    this.broadcastService.broadcast('msal:notAuthorized', err.message);
                                }
                            }
                        )
                    );
            }

So in the above code it goes to the error but it never enters this.authService.handleRedirectCallback can someone please help me with this. I need the token to be renewed.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:9
  • Comments:89 (16 by maintainers)

github_iconTop GitHub Comments

9reactions
anth-gitcommented, Jul 28, 2020

I think I managed to get it working even for high POLLING_INTERVAL_MS values:

@NgModule({
  imports: [RouterModule.forRoot(routes,
    {
      enableTracing: false,
      useHash: true,
      initialNavigation: isInIframe() ? 'disabled' : undefined // <-THIS
    })],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

export function isInIframe() {
  return window !== window.parent && !window.opener;
}
2reactions
rpapeterscommented, Oct 20, 2020

I’ve been able to resolve the token timeout issue by following the common issues guide found here: Common Issues

In our setup we had a redirect in the angular router from ‘/’ to ‘/some-url’ and we where redirecting msal to ‘/’, which would trigger a redirect by angular while acquiring the token. Msal did not like that. Now we have a redirect to (in our case) ‘/msal’ for msal, without angular redirecting under the hood and the problem seems to be resolved. Don’t forget to add the ‘/msal’ as an authenticated Redirect URI in the app registration in Azure Ad (B2C).

Read more comments on GitHub >

github_iconTop Results From Across the Web

Token renewal operation failed due to timeout MSAL Angular ...
Thats all working fine. But sometimes I am getting an error. Uncaught (in promise): ClientAuthError: Token renewal operation failed due ...
Read more >
External module "error/ClientAuthError" - msal
desc: string = "Token renewal operation failed due to timeout." Defined in error/ClientAuthError.ts:30. userCancelledError. userCancelledError: object.
Read more >
More from Jayapragash - Medium
Regarding acquiring access tokens to authenticate http requests it's working fine ... "token renewal operation failed due to timeout. msal" ...
Read more >
Token renewal operation failed due to timeout..
I am trying to export to Excel, and I am getting an "Authentication error". I logged out and try to log back in......
Read more >
ADAL.JS Token renewal operation failed due to timeout error
My code tries to authenticate the logged in user by getting the cached token. If the chached token is null, I use acquireToken...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found