Microsoft-authentication-library-for-js: MSAL Guard on redirect URI causes: Token renewal operation failed due to timeout.

Created on 1 Feb 2020  路  39Comments  路  Source: AzureAD/microsoft-authentication-library-for-js

Please follow the issue template below. Failure to do so will result in a delay in answering your question.

Library

Important: Please fill in your exact version number above, e.g. [email protected].

Framework

If you are using a framework, please provide the framework and version (e.g. Angular v8, React v16, etc).
Angular 7

Description

I upgraded to my code to [email protected]. Since then, i got most of the time token renewal error. Sometimes it works sometimes not.

Below you find the error that i get:
ERROR ClientAuthError: URL navigated to is https://login.microsoftonline.com/6e5433e0-76fc-44b7-b71b-0e5446a3fa94/oauth2/v2.0/authorize?response_type=token&scope=user.read%20user.read.all%20openid%20profile&client_id=XXXXX&redirect_uri=https%3A%2F%2Flocalhost%3A44321%2F&state=2c239776-194a-4dd1-9ffd-5ef6a8170bfb&nonce=64ebf40a-c982-4d0f-947a-008486098f0e&client_info=1&x-client-SKU=MSAL.JS&x-client-Ver=1.2.1&login_hint=XXXXt&login_req=69fe329f-7029-47ae-9640-35f2b80d3dc7&domain_req=6e5433e0-76fc-44b7-b71b-0e5446a3fa94&domain_hint=organizations&client-request-id=d5399407-a9b0-449f-bacb-c51b451f341c&prompt=none&response_mode=fragment, Token renewal operation failed due to timeout.
at t [as constructor] (https://localhost:44321/main.85b343060f18cba93e8d.js:1:522654)
at new t (https://localhost:44321/main.85b343060f18cba93e8d.js:1:523276)
at Function.t.createTokenRenewalTimeoutError (https://localhost:44321/main.85b343060f18cba93e8d.js:1:524233)
at https://localhost:44321/main.85b343060f18cba93e8d.js:1:545696
at e.invokeTask (https://localhost:44321/polyfills.ad66e791a6ddbd9fe3e0.js:1:8059)
at Object.onInvokeTask (https://localhost:44321/main.85b343060f18cba93e8d.js:1:193339)
at e.invokeTask (https://localhost:44321/polyfills.ad66e791a6ddbd9fe3e0.js:1:7980)
at t.runTask (https://localhost:44321/polyfills.ad66e791a6ddbd9fe3e0.js:1:3241)
at t.invokeTask (https://localhost:44321/polyfills.ad66e791a6ddbd9fe3e0.js:1:9142)
at invoke (https://localhost:44321/polyfills.ad66e791a6ddbd9fe3e0.js:1:9033)

Security

Is this issue security related?

Regression

Did this behavior work before?
I had no issue related to timeout with version 0.1.4

Configuration

MsalModule.forRoot(
{
auth: {

      clientId:"xxxxxxx",
      authority:"https://login.microsoftonline.com/tenantid",
      postLogoutRedirectUri:"https://login.microsoftonline.com/tenantid",
      validateAuthority:true  ,
      navigateToLoginRequestUrl: true,  
    },
    cache:{

      cacheLocation:"localStorage",
      storeAuthStateInCookie:isIE
    },
    system:{
      loadFrameTimeout:35000,
    }
  },
  {
    popUp: false,
    consentScopes: ['user.read','user.read.all','https://domain.net/api-access'],
    protectedResourceMap,
    unprotectedResources:["https://www.microsoft.com/en-us/"],
    extraQueryParameters: {}
  }
// Provide configuration values here.
// For Azure B2C issues, please include your policies.

Reproduction steps

  1. Logout,
  2. Login,
  3. Call authorized endpoint,
    3.1 In my case i load some data from graph api with its scope and another data from my web api. After login i can acquire toke for one of the both and for the second it fails to obtain access token.
    3.2 It also happened on token renewal.

Expected behavior

no timeout error should be returned when trying to acquire token. specially after fresh login

Browsers

Is this issue browser-specific? If so, please detail which browsers are impacted (e.g. IE 11, Safari).
I tried this on Chrome and IE edge

bug msal-angular

All 39 comments

I see the error AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint in the URL listed in the time out.

msal js times out when the error is not redirected by the service to the application in certain cases. As an alternative, we provide the URL in our error message for the user to be able to discern the cause of the failure. In this case I am not sure why your session cookies are cleared, which could cause this error.

To help is address this, can you please share your sample code for authentication, and a fiddler trace if possible?

Hello Sameera,

Thanks for your answer. Below you find my comments:
I see the error AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint in the URL listed in the time out. --> i cannot see this error. How did you see it ?

How can i get the error message from the url ?

As an alternative, we provide the URL in our error message for the user to be able to discern the cause of the failure. I

In this case I am not sure why your session cookies are cleared, which could cause this error.
I call this.auth.logout(); when i logout from the system (auth is MsalService). Do i have to do something else in order to clear session cookies ?

For authentication i am using msal guard so the system tries to login automatically.
```
if(!Utilities.isIFrame())
{

this.broadcastService.subscribe("msal:loginFailure", (payload) => {
console.log("login failure " + JSON.stringify(payload));
if(payload.name=="InteractionRequiredAuthError")
{
this.auth.loginRedirect();
}
this.loggedIn = false;
});
this.broadcastService.subscribe("msal:acquireTokenSuccess", (payload) => {
// do something here
console.log("acquireToken success", payload);
});
this.broadcastService.subscribe("msal:acquireTokenFailure", (payload) => {
// do something here
console.log("acquireToken failure", payload);
});
this.broadcastService.subscribe("msal:loginSuccess", (payload) => {
console.log("success triggerd " , this.loggedIn);
if(!this.loggedIn&&!window.location.href.includes("id_token"))
{
this.configurationService.initialize();
this.userService.getMyCVs();
this.userService.getGroup();
}
this.loggedIn = true;
});

this.auth.handleRedirectCallback((redirectError: AuthError, redirectResponse: AuthResponse) => {
if (redirectError) {
console.error("Redirect error: ", redirectError);
return;
}
console.log("Redirect success: ", redirectResponse);
});
```

As a temporary work around for this. I had to do a dirty solution by creating a custom interceptor that retries two time to recall the acquireTokenSilent. It seems to solve the problem in most of the cases but once it called acquireTokenSilent 3 times and i got 3 times timeout error.

Here is my Custom Interceptor Code :
`import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BroadcastService, MsalService } from '@azure/msal-angular';
import { UserAgentApplication, AuthResponse } from 'msal';
import { Observable, from, of } from 'rxjs';
import { mergeMap, tap } from 'rxjs/operators';
@Injectable()
export class CustomInterceptor implements HttpInterceptor {
constructor(private auth: MsalService, private broadcastService: BroadcastService) { }

intercept(req: HttpRequest<any>, next: HttpHandler):  Observable<HttpEvent<any>> {
const scopes = this.auth.getScopesForEndpoint(req.url);
console.log("new request", req);

//this.auth.getLogger().verbose('Url: ' + req.url + ' maps to scopes: ' + scopes);
    if (scopes === null) {

        return next.handle(req);
     }

     let accessToken: string;

     // Acquire a token for this request, and attach as proper auth header.
     return from(
         this.auth.acquireTokenSilent({ scopes })
             .then((response: AuthResponse) => {
                 accessToken = response.accessToken;
                 const authHeader = `Bearer ${response.accessToken}`;
                 return req.clone({
                     setHeaders: {
                         Authorization: authHeader,
                     }
                 });
             },error=> {

                 console.log("Acquire token silentily interceptor failed. Trying again",scopes,req);
            return  this.auth.acquireTokenSilent({ scopes,forceRefresh:true })
                .then((response: AuthResponse) => {
                    accessToken = response.accessToken;
                    const authHeader = `Bearer ${response.accessToken}`;
                    return req.clone({
                        setHeaders: {
                            Authorization: authHeader,
                        }
                    })},error=>{

                    console.log("Acquire token silentily interceptor failed 2. Trying again",scopes,req);
                       return  this.auth.acquireTokenSilent({ scopes,forceRefresh:true })
                           .then((response: AuthResponse) => {
                               accessToken = response.accessToken;
                               const authHeader = `Bearer ${response.accessToken}`;
                               return req.clone({
                                   setHeaders: {
                                       Authorization: authHeader,
                                   }
                               })});
                    });                 
            })
     )
     .pipe(

         mergeMap(nextReq => next.handle(nextReq)),
         tap(
             event => {},
             err => {
                 if (err instanceof HttpErrorResponse && err.status === 401) {
                     this.auth.clearCacheForScope(accessToken);
                     this.broadcastService.broadcast('msal:notAuthorized', err.message);
                 }
             }
         )
     );
}

}
`

I hope this can help investigating the issue. I will install Fiddler and send you more details.

Best regards,
Emad

Hello,

I have some more information. Some times even the retry 3 times cannot work. ON IE i see the following warning message:

Security of a sandboxed iframe is potentially compromised by allowing script and same origin access

Best reagards,
Emad

The above warning can be ignored as msal js isn't sandboxing the iframe for security purpose.

For your question:

I see the error AADSTS50058: A silent sign-in request was sent but none of the currently signed in user(s) match the requested login hint in the URL listed in the time out. --> i cannot see this error. How did you see it ?

I have clicked the below link you provided in the original issue desc. The idea is that for some errors which aren't sent back to the client after a redirect from the service, and hence resulting in msal js timing out, we provide a URL for the user to click in the error messaging to check why the error is happening.

ERROR ClientAuthError: URL navigated to is https://login.microsoftonline.com/6e5433e0-76fc-44b7-b71b-0e5446a3fa94/oauth2/v2.0/authorize?response_type=token&scope=user.read%20user.read.all%20openid%20profile&client_id=XXXXX&redirect_uri=https%3A%2F%2Flocalhost%3A44321%2F&state=2c239776-194a-4dd1-9ffd-5ef6a8170bfb&nonce=64ebf40a-c982-4d0f-947a-008486098f0e&client_info=1&x-client-SKU=MSAL.JS&x-client-Ver=1.2.1&login_hint=XXXXt&login_req=69fe329f-7029-47ae-9640-35f2b80d3dc7&domain_req=6e5433e0-76fc-44b7-b71b-0e5446a3fa94&domain_hint=organizations&client-request-id=d5399407-a9b0-449f-bacb-c51b451f341c&prompt=none&response_mode=fragment, Token renewal operation failed due to timeout.

I think we can use some change of messaging here, which I will track separately. More details about errors like this are mentioned in issue #1199 and the documentation of these types of errors is in the pipeline.

@jasonnutter Is it possible that the retry in angular automatic even after silent sign in failure?

Hello Sameerag,

First of all thanks for your following. You are right the link above give silent login failure. I found that it was only the url i put here with this issue. I clicked on another timeout error message and i was redirected to the app successfully. I investigated further and clicked on other links where i had this problem on Chrome and IE Edge and i got the following conclusion.

The problem flow is as below:
1- MSAL sends a request to the authorize endpoint,
2- The authorize endpoint redirect correctly to the redirect url inside my angular app (i put a console.log and i saw the redirected Iframe).
3- The a reason was not known for me before. The application doesn't capture the token ot error message from the Iframe.

But after looking again to my configuration. I put MsalGuard on the redirect url route. I doubt that the IFrame is getting redirected to the login page within the Iframe because of this MsalGuard attribute on that route. I removed the MsalGuard from thr App Routing and i added the login request manually in my code when the account is null and not Iframe and i believe that should have resolved my problem.

Since i have done the solution above (since yesterday), i don't get anymore the timeout issue on Chrome and IE Edge. but i get sometimes one timeout fail on IE11 (in that case no redirect from the authorize endpoint has been sent back). And starting from the second retry it get the token successfully on IE 11.

Could you confirm me that MsalGuard on the redirect url could cause another redirect within the Iframe or not ?

Best regards,
Emad

To avoid something similar, we are doing this, to forze user go to login:

this.broadcastService.subscribe('msal:loginFailure', ()=> {
      this.auth.loginRedirect();
});

@emadalsous Correct, putting the MsalGuard on your redirect URI could cause another redirect and thus a timeout. I'll see if we can make the guard smarter such that it doesn't cause the redirect when it is loaded inside a hidden iframe. Note that since [email protected], you can set your redirect uri for silent/popup requests to a page that has no content at all (e.g. a blank html page), and that you can set redirectUri per request (in case you need to also make redirect requests).

@jasonnutter Removed the MsalGuard off the redirect URI and that seems to have solved the issue for me.

this error persists I'm using msal 1.2.1, any solution? Your solution @luklew does not work for me.

@brayanL Timeouts can happen for a number of reasons, so any investigations you can do in your app to determine what might be causing your timeouts would be helpful, thanks!

Hey @jasonnutter I'm also hitting the timeout issue randomly (more often than not) and have also removed MsalGuard from the root route of the app, which is our redirect URI. Something is not right when the app in the main frame tries to obtain the hash from the nested iframe. This happens when the MsalInterceptor runs and acquireTokenSilent runs. I've also applied the technique in your latest Angular sample where we don't fully run the app when in an iframe (where the router-outlet is not rendered) but that doesn't help either. I'll try to dig further to find the cause, but right now this is quite a blocker.

1.2.2-Error Error when acquiring token for scopes: api://[aad_app_uri_redacted]/user_impersonation ClientAuthError: URL navigated to is https://login.microsoftonline.com/[tenantid_redacted]/oauth2/v2.0/authorize?response_type=token&scope=[api_scope_redacted]%2Fuser_impersonation%20openid%20profile&client_id=[clientid_redacted]&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2F&state=[state]&nonce=[nonce]&client_info=1&x-client-SKU=MSAL.JS&x-client-Ver=1.2.2&login_hint=[login_hint_redacted]&login_req=[guid]&domain_req=[guid]&domain_hint=organizations&client-request-id=06ccc6ca-39d5-4e36-9e02-bad184d1b055&prompt=none&response_mode=fragment, Token renewal operation failed due to timeout.

"@azure/msal-angular": "1.0.0-beta.2"
"msal": "1.2.2-beta.0"

Hey @jasonnutter I have found the cause of the timeouts in our app.

We are using HashLocationStrategy in our app by setting useHash: true in our app routing module because we need to serve the app via CDN with no extra web server configuration for Angular routing. With the previous msal-angular 0.1.4-beta.2 I had applied a hack in our app where I added all possible MSAL hashes so that the app did not error out after a redirect back from AAD to the app within the hidden iframe used by MSAL. The code looked like this:

const routes: Routes = [
  { path: '', component: DashboardComponent, pathMatch: 'full' },
  // More legit app routes go here.

  // Hash routes used by MSAL.
  // These must appear here so that Angular knows about these "routes".
  // Sourced from here: https://git.io/Jelf3
  { path: 'access_token', redirectTo: '' },
  { path: 'id_token', redirectTo: '' },
  { path: 'error', redirectTo: '' }
];

The "hack" caused a redirect back to the root route in the app within the hidden MSAL iframe. This worked fine in the old msal-angular but broke when upgrading to msal 1.2.2-beta.0 and @azure/msal-angular 1.0.0-beta.2 because the Angular redirect would reset the hash and therefore the access_token before MSAL in the parent window could consume it.

After some more digging, I found that one can disable the initial navigation of the Angular router, which is exactly what I would want to happen within the hidden iframe so that MSAL can successfully parse the hash without the interference from the Angular router. The following now works with for me, performance is much better, and I also no longer need to have the dummy MSAL hash routes defined in the app routing module:

const routes: Routes = [
  { path: '', component: DashboardComponent, pathMatch: 'full' },
  // More legit app routes go here.
];

// MSAL uses a hidden iframe to obtain access tokens. Specifically,
// MSAL causes a redirect to AAD and then back to the app with the
// access token in the URL hash, all within the hidden iframe.
// The app is then loaded again within the hidden iframe, which is
// undesirable for performance reasons but more importantly, the
// Angular router will mess up the hash if using HashRoutingStrategy.
// For this reason, we disable the initial navigation of the Angular
// router if we're in an iframe.
const isIframe = window !== window.parent && !window.opener;

@NgModule({
  imports: [
    RouterModule.forRoot(
      routes,
      {
        enableTracing: false,
        paramsInheritanceStrategy: 'always',
        useHash: true,
        initialNavigation: !isIframe
      }
    )
  ],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule {
}

I hope in future using MSAL Angular with HashLocationStrategy is easier. I would propose that MSAL Angular allows for a silentTokenAcquisitionRedirectUri to be specified in its configuration so that consumers can specify a blank html page, then MSAL Angular can send this value in the redirectUri field of the AuthenticationParameters when acquiring tokens silently. That way the Angular app would not need to be loaded at all in the hidden iframe.

@Ivan-L Thanks for the context!

Since [email protected] your redirect URI no longer has to have MSAL running on it (which was a previous requirement), which means you can set your redirect URI to be a page with no content on it for silent and popup flows (as you propose). You can also set the redirectUri per request, so that you can set the default redirectUri to be a blank page, and then explicitly set it for other requests (e.g. redirect flows, which still require MSAL to be running on redirect).

Hi @jasonnutter thanks for the feedback.

Yes, [email protected] does have the ability to set the redirectUri per request so that it can redirect to a blank HTML page for silent and popup flows, however the MsalInterceptor and MsalGuard in @azure/[email protected] do not allow for a custom redirectUri for those flows. Check out the acquireTokenSilent calls here and here where the only parameter set for each request is the scopes. This is why I was proposing an extra property on MsalAngularConfiguration (such as something like silentTokenAcquisitionRedirectUri) so that the MsalInterceptor and MsalGuard can use that config value and set it as the redirectUri per request. Otherwise, if we did want to specify a custom redirectUri per request to take advantage of what is offered in [email protected], we would need to write our own version of MsalInterceptor and MsalGuard, which kind of defeats the purpose of @azure/msal-angular I think?

Of course, if I have got this all wrong, then please do correct me 馃槃

I found the solution, my problem was redirectUri and postLogoutRedirectUri params on authProvider File, both on Azure Portal and authProvider File the URLs should be the same, I had on azure portal http://locahost:3000/ but on authProvider File was http://localhost:3000/login. I hope this can help someone.

@Ivan-L You are correct, and I agree that you should have the ability to do that. Note that for now, if you aren't using one of the redirect flows (loginRedirect or acquireTokenRedirect) you can set the default redirectUri to a blank page. I'll follow up when I have more on this.

@brayanL Makes sense, thanks for the update!

@Ivan-L Follow up, you should be able to pass additional options to the MsalGuard by providing an object for extraQueryParameters, which will get added to the request the guard makes.

MsalModule.forRoot({
  // msal base config
}, {
  extraQueryParameters: {
    'redirect_uri': 'http://domain.com/path/for/guard/redirect'
})

These options don't get added to the interceptor, however, and I'm strongly considering changing this options object to allow you to do that.

PR to short-circuit the guard if used on a redirect URI is up: #1337

Will release in the next beta.

FYI: the same issue happens for me with Safari only.
Error when acquiring token for scopes: ClientAuthError Token renewal operation failed due to timeout.

it's just basic flows and so poor handling, camon we shouldn't apply any workarounds,
we're using it for enterprise products with solid budgets and getting so annoying issues.

"msal": "^1.2.2",
"@azure/msal-angular": "^1.0.0-beta.4".

@kemins we are in a similar boat, but keep in mind that you are using a beta version of something for your enterprise products (sounds like in production), and that's not really something that is this library's fault.

FYI: the same issue happens for me with Safari only.
Error when acquiring token for scopes: ClientAuthError Token renewal operation failed due to timeout.

@kemins To clarify, when you have the MSAL Guard set on your redirect uri, you are receiving a timeout error in Safari?

FYI: the same issue happens for me with Safari only.
Error when acquiring token for scopes: ClientAuthError Token renewal operation failed due to timeout.

@kemins To clarify, when you have the MSAL Guard set on your redirect uri, you are receiving a timeout error in Safari?

no, MSAL Guard is not applied on redirection uri, redirection URL is a root angular rout, MSALGuard activated only for children routes.

it works fine with chrome and safari on mobile devices,
but fails on safari desktop version(in incognito without any plugins)

overall its' straightforward configuration with:

  • consentScopes,
  • MsalInterceptor
  • MsalGuard (not on redirection uri)
  • routes - html5 mode(not hashbang)

Hello Jason,

FYI, I think that MSAL doesn't work at all for the moment with Safari. We cannot access the Token for Safary security issues.

Best regards,
Emad

Hello,

I am also getting issues with tokens, but on safari / chrome iOS devices only. When I attempt to login it goes into an infinite loop where it's trying to redirect to Microsoft login page and my redirect URL and them back to Microsoft login etc... It seems to happen around 50% of the time, sometimes it logs in no problem .

@kemins we are in a similar boat, but keep in mind that you are using a beta version of something for your enterprise products (sounds like in production), and that's not really something that is this library's fault.

agree) probably we will try with a custom approach.

@kemins @emadalsous @luklew Can you please confirm whether or not third-party cookies are blocked? It is known that the library will not work if third-party cookies are disabled (e.g. via Safari ITP).

@jasonnutter It seems to be intermittent, sometimes it works on the same device / browser, and sometimes it will go into a infinite loop of calling login.microsoft and redirecting to my app. I have a video I can show you , or maybe jump on a call with you to try and demonstrate my code setup to see if you can find any issues with it ?

@luklew A video and a Fiddler trace would be helpful, can you please email those to me? Thanks!

@jasonnutter Sent an email to you. Thanks!

@kemins @emadalsous @luklew Can you please confirm whether or not third-party cookies are blocked? It is known that the library will not work if third-party cookies are disabled (e.g. via Safari ITP).

@jasonnutter Thanks for looking,
Third-party cookies should be enabled, IMHO I guess it's somehow connected with consentScopes.

image

From console:
-Error Error when acquiring token for scopes ....: ClientAuthError: URL navigated to is https://login.microsoftonline.com/...../oauth2/v2.0/authorize?response_type=token&scope=...%6Fmyscope%6openid%6profile&client_id=....&redirect_uri=http%6A%6F%6Flocalhost%6A4200%6F&state=0c587f20-7607-4de8-8c51-15ea50578370&nonce=732629e2-9b9f-4f98-b60a-2924cbf49fd0&client_info=1&x-client-SKU=MSAL.JS&x-client-Ver=1.2.2&login_hint=TEST.USER2%6PETHLAB.COM&login_req=0d2f4378-36be-4ec4-99e7-bfe660afa8b3&domain_req=8b24551d-7c2c-4beb-8b61-95f32d9929ef&domain_hint=organizations&client-request-id=38e70e2b-147d-498a-98ac-8fb16d18c2ef&prompt=none&response_mode=fragment, Token renewal operation failed due to timeout.

@kemins What happens if you open that url directly in its own tab?

Also, that redirectUri doesn't look correct, decodes to httpjoolocalhostj4200o, which doesn't seem correct.

Hi all,

I am also having the same issue for the renew token failed due to timeout.
The problem is that it is only happening for the first time when I login, like it was renewing non existing token.

MsalGuard is not on the root of the redirectUri, my redirectUri is the root of my application, and it also does not have MsalGuard on it, but it redirects to the '/loading' screen, that screen does have MsalGuard, and it also has the first API call since we are using API for role authentications.

The first call to the API requests an access token wich of course sends the error message and does not complete.

We were trying to reload the page after that error and for some reason it works, but not all the time.
This issue does not happen when working in localhost.

Do we need to watch out for some kind of race condition? Because we are not calling the API unless we get logged in first.

Thank you.

UPDATE
Just to say that we are getting the ID token, which quilfy us to be loged in.

This happens on Edge and Chrome.
The reproducable steps were that once we open the app and login first time we are getting the acces token for our API.
If we close the browser which clears our cache, and session storage, once we get the ID token and get loged in, the first API call returns with the error:

'ClientAuthError: URL navigated to is...' ' Token renewal operation failed due to timeout.'

Hello eynenad,

You shouldn't redirect to the loading component until you have a valid user object with valid token. And you shouldn't redirect at all in the 2 cases:
1- When the screen is IFrame (your application is reloaded when the renew token or the login occurs but inside an IFrame)
2- When it is not an IFrame but the query string contains id token parameters (microsoftlogin redirect to your redirectUri after the user login).

You can also make the redirect url be an empty page when renewing the token silently.

Best regards,
Emad

Hi @emadalsous ,
I am facing this issue in my application the same as mentioned by you. I haven't given a msal guard for my redirect URI, but that is not a blank HTML page. Basically, I don't have a login page when the user enters the URL on the browser, it redirects the user to login.microsoft.com URL and prompts to enter the user email which will authenticate the user against Azure Ad and send back the token and enable the user to see the application after successful redirection. But if I click on any of the pages after a few seconds I am getting the error "Token renewal operation failed due to timeout".

"msal": "^1.2.2",
"@azure/msal-angular": "^1.0.0-beta.4".

Any suggestions would be really helpful. Thanks in advance. Please let me know if you need more info on the same.

Hello Jithesh,

What is your redirectURI ? Do you have any redirection in that component to a component that do authentication or has MSALGUARD ? this could cause an issue. If you don't want to set a black page for the acquireTokenSilently, i would suggest that you don't render the router-outlet in the app component html by using ngIf when the page is an IFrame (check Angular example to know how to find when the page is requested within an IFrame). This will setup freeze any routing functionality in your application when it's open from IFrame. I hope this could help.

Best regards,
Emad

Thanks a lot @emadalsous for the quick response.
Yes, I am not using the IFrame and not setting the route-outlet with ngif for the same.
For the time being, I kept the redirect URL without MSAL Guard (but not a blank html page) and only clicking on any of the page actually initiates the routing and guarded with MSAL (which should change in future, I kept like that to see whether that could resolve the timeout issue).
Since I am new to this, could you please suggest what should be the ideal way to do this ?
Once again thanks..!! :)

The same issue with: "@azure/msal-angular": "1.0.0" and Safari only(Third-party cookies enabled)
when trying to acquire an access token for the consentScopes.

Error when acquiring token for scopes ....: ClientAuthError: URL navigated to is https://login.microsoftonline.com/...../oauth2/v2.0/authorize?....

The only difference it's not beta anymore))

Works fine with chrome so there's nothing wrong with configuration.

@kemins can you please tell me what is the setup/configuration that you did? Where did you put msal guard, interceptors, and such....) I still sometimes have the same issue on Chrome, Edge, IE, we do not use Safari, so I haven't checked on that browser.
The issue is not that common, but happens sometimes, I would really like to avoid happening alltogether.

I don't think that it is your @kemins setup. And would really appreciate your assistance on this.
Thank you.

hi @eynenad

MSALGuard is placed at the child route level, root route is free of MSAL guard.

Overall my configuration is pretty typical nothing special.

MsalModule.forRoot(
      {
        auth: environment.auth,
        cache: environment.cache as unknown,
        system: {
          logger: new Logger(LoggerService.instance.log, {
            level: LogLevel.Error,
            piiLoggingEnabled: true,
          }),
        },
      },
      {
        protectedResourceMap: [
          [
            environment.serviceBaseUrl, [
              ...environment.consentScopes || [],
            ],
          ],
        ],
        unprotectedResources: [
          '/assets/',
        ],
        consentScopes: environment.consentScopes,
      },
    ),

// interceptor in AppModule providers:
[{ provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true } ]

// environment.ts
 auth: {
    authority: 'https://login.microsoftonline.com/your authority id,
    clientId: 'your client id,
    navigateToLoginRequestUrl: false,
    redirectUri: () => `${ window.location.origin }/`,
  },
  consentScopes: ['https://peth365dev.onmicrosoft.com/your scope],
  cache: {
    cacheLocation: 'localStorage',
  },


// User service (in my case) triggers init and handles MSAL callbacks
 public init(): void {
    if (environment.sso) {
      this.msalService.handleRedirectCallback(() => { });
      // optional redirection to initiator instead of default route
      this.subscriptions.push(this.broadcastService.subscribe('msal:loginSuccess', this.redirectToInitiator));
      this.subscriptions.push(this.broadcastService.subscribe('msal:acquireTokenFailure', this.login));
    }
  }

  public login(): void {
    this.msalService.loginRedirect({
      scopes: environment.consentScopes,
    });
  }

package.json
"@azure/msal-angular": "^1.0.0",
"msal": "^1.3.1",

But my pain is still Safari on MacOS(fine with IOS), renew token failing due to timeout even with a workaround:
https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/Known-issue-on-Safari

Was this page helpful?
0 / 5 - 0 ratings