getToken() intermittently hangs and fails to resolve/reject
Category
- [ ] Question
- [ ] Typo
- [x] Bug
- [ ] Additional article idea
Expected or Desired Behavior
The promise returned by AadTokenProvider.getToken() should always resolve or reject. In other words, when a token can't be retrieved for whatever reason, I should get something back that I can catch.
Observed Behavior
getToken() is occasionally hanging - never resolving or rejecting so I can't catch an error or figure out what's happening. The .then() under getToken() just never runs and my web part stalls.
Steps to Reproduce
I'm trying to access a .NET Core Web API secured with AAD from my custom web part. I initially used the instructions found here but AadHttpClient.get() was occasionally stalling so I decided to get the token using AadTokenProvider.getToken() and manually add it to a HttpClient.get() but my issue didn't go away. I was however able to confirm that getToken() is where it hangs rather than an issue with the API. Here's my code:
this.context.aadTokenProviderFactory.getTokenProvider()
.then((provider) => {
return provider.getToken('<Client ID for my API>', false) //THIS IS WHERE IT HANGS
.then((token) => {
this.context.httpClient
.get('https://www.example.com/api/myAPI/', AadHttpClient.configurations.v1, {
headers: [
['accept', 'application/json'],
['Authorization', 'Bearer ' + token]
]
})
.then((res: HttpClientResponse): Promise<any> => {
return res.json();
})
.then(data => {
//process data
}, (err: any): void => {
this.context.statusRenderer.renderError(this.domElement, err);
});
}, (rejection) => {
this.context.statusRenderer.renderError(this.domElement, "Token request rejected. " + rejection);
});
})
.catch((err) => {
this.context.statusRenderer.renderError(this.domElement, "Failed to get token provider.");
});
I noticed that it seems to hang after a period of inactivity like maybe it's failing to refresh a stale token or something. I'd expect the rejection code to execute but nothing beyond getToken() runs. But if I refesh the page a couple times, it starts working again.
This seems to be related to issue #914 reported on pnp/pnpjs.
Edit: I discovered that this is a lot easier to reproduce in Chrome. (I haven't seen it occur in IE and I've only seen it once or twice in Firefox although I can't seem to reproduce in FF at the moment. Edge gets the token but fails the API request for reasons I can't explain). In Chrome, it struggles every time it needs to grab a token. So, for example, it hangs the first time you load the page. If you refresh a few times, it starts working. Then if you leave the page open for a period of time (long enough for the token to expire) and refresh the page, it hangs again.
Edit 2: Per the conversation below, we can reproduce the issue when the custom web part is on the same page as a document library and a planner or events web part and it works fine when on a page by itself. There may be some sort of conflict with token retrieval/sharing between web parts.
Thank you for reporting this issue. We will be triaging your incoming issue as soon as possible.
I spotted the following message in the console when it errored referring to mytenant.sharepoint.com/_forms/spfxsinglesignon.aspx:
Blocked script execution in '
<URL>' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.
@TheIronCheek said:
I noticed that it seems to hang after a period of inactivity
What do you mean by "period of inactivity?... you mean the page sitting open for a while? If so, how long is "period of inactivity"?
Long enough for the token to expire... a half hour maybe?
The problem seems to happen most consistently in Chrome. It looks like it happens whenever it needs a fresh token. So, the very first time the user hits the page, it fails. If you refresh the page a few times, it'll finally get a token. And then it fails again when that token expires and it tries to get a new token.
Any chance you have a sample project you can share (via public GH repo) to repro it? Will help speed up the repro to escalate the issue to engineering...
I'll throw something together for you.
Sounds like after obtaining a token, SPFx just keeps using the same, but not handling the response if the token is expired. Have you inspected the request with Fiddler / network tab in the browser? When the request is made, I expect you'll see a response saying something like the token has expired... my theory is that this response isn't handled by the SPFx API and thus, they the promise is never resolving...
There are hundreds of requests being made on the page but watching the Network tab on a successful run, here's what I'm gleaning that looks pertinent:
- It makes a GET request to
https://login.microsoftonline.com/<tenant>/oauth2/authorizeand the response is a302 Foundwith Location header set tohttps://<tenant>.sharepoint.com/_forms/spfxsinglesignon.aspx#access_token=<token>. - Shortly after, it expectedly sends a GET request to
https://<tenant>.sharepoint.com/_forms/spfxsinglesignon.aspxthat responds with a200and setsFedAuthandrtFacookies. - Shortly after that, it sends an OPTIONS request to my API and the API returns
204 No Content - It finally makes the GET request with the Authorization header set so that my API returns the actual data.
On a failing run, here's what I get:
- The same GET request to
https://login.microsoftonline.com/<tenant>/oauth2/authorizeand the same302 Foundresponse that has Location set in the header tohttps://<tenant>.sharepoint.com/_forms/spfxsinglesignon.aspx#access_token=<token>. - The same GET request to
https://<tenant>.sharepoint.com/_forms/spfxsinglesignon.aspxthat responds with a200and setsFedAuthandrtFacookies. - My API is never called.
Based on that, it looks like a token is being correctly retrieved since that Location header value in the response from https://login.microsoftonline.com has the access_token URL parameter set to a value. But for whatever reason, that token never makes it back to my web part so it can call my API.
Like I said, there are hundreds of requests that run here so it's tough to sift through and figure out what's relevant. If there's something specific I should look for, let me know.
I updated the OP with browser specific information.
I threw together a sample web part:
https://github.com/TheIronCheek/SampleWebPart
I have the exact same issue as you.
@andrewconnell Do I need to open a new issue ? Or submit a msft support request to speed things up ?
@FlorianLabranche - I'm glad I'm not the only one. If you figure out what's going on, please - for the love of all that is holy - come back here and update me. I'll be sure to do the same. I have a ticket open with support too and I was told they're "escalating" the issue and that I'd for sure get a call back today. Still waiting.
Googling around today, I found this resolved issue from late October/early November.
It references the same message I get:
Blocked script execution in '
<URL>' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.
But in that situation, it only affected extensions and not web parts. Could my issue be tangentially related?
I am seeing simmilar issues. Might be something else, but maybe it helps to track down the issue... For me this only happens if thre is an OOTB document libraray/list webpart on the page or a planner webpart. I think those ootb webparts are also getting a token for MS graph using the underlying adal infrastructure and interfering with the custom webparts. Looking at the tokens in the session storage of the browser, you can see that things get messed up. Removing those ootb webparts and refreshing the page, i can get my token without any problems over and over again...
@OliverZeiser - I put my custom web part on a blank page with no other web parts to test a couple weeks ago and the problem didn't go away.
Although when I try it now, it seems to work fine on its own page...
Well now try to put a doc lib and planner webpart on the same page and try again a few times...
@OliverZeiser - I don't have the planner web part but I was able to reproduce the issue with a doc library and event web part (both of which are also on my main page).
I think we're onto something here.
@TheIronCheek I've checked multiple samples I use to demonstrate this and all seem to be working as expected. They are:
- Use AadHttpClient to call an OOTB secured endpoint (MS Graph)
- Use AadHttpClient to call a custom secured endpoint (REST API hosted with secured Azure Function)
- Use MSGraphClient to call MSGraph
All of these use the same underlying infrastructure to obtain a token. I tested them individually & combined being the only web part on the page, with all of them on the page, and also with other OOTB web parts on the page (including the Document Library web part). I've been refreshing the pages and hitting them every other day and none of them are breaking. I'm trying, but I can't repro what you guys are saying.
I see two things in your code... one isn't terribly important, the other I suspect is your issue. I am not seeing the stalling out using the AadHttpClient.getClient()... I see you switched to AadTokenProvider.getToken()... that won't fix anything as you're now just doing the same thing the AadHttpClient does for you.
However, I see you're trying to reference your endpoint by the client ID... a GUID. That was supported in the dev previews, but that's not supported or how you're supposed to do it how. That value should be the endpoint of the service you are trying to reach. Look at the definition of the underlying getToken() method:
/**
* Fetches the AAD OAuth2 token for a resource if the user that's currently logged in has
* access to that resource.
*
* The OAuth2 token should not be cached by the caller since it is already cached by the method
* itself.
*
* @param resourceEndpoint - the resource for which the token should be obtained
* @param useCachedToken - Allows the developer to specify if cached tokens should be returned.
* An example of a resourceEndpoint would be https://graph.microsoft.com
* @returns A promise that will be fullfiled with the token or that will reject
* with an error message
*/
getToken(resourceEndpoint: string, useCachedToken?: boolean): Promise<string>;
Notice it's the endpoint... and the reference is the URL of the endpoint.
The AadHttpClient method says the same:
/* Excluded from this release type: __constructor */
/**
* Returns an instance of the AadHttpClient that communicates with the current tenant's configurable
* Service Principal.
* @param resourceEndpoint - The target AAD application's resource endpoint.
*/
getClient(resourceEndpoint: string): Promise<AadHttpClient>;
For reference, here's how I'm calling a custom service...
const NASA_APOLLO_MISSION_ENDPOINT_URI: string = 'https://voitanos-secure.azurewebsites.net';
export class MissionService {
constructor(private aadHttpClientFactory: AadHttpClientFactory) { }
public getMissions(): Promise<IMission[]> {
return new Promise<IMission[]>((resolve, reject) => {
this.aadHttpClientFactory
.getClient(NASA_APOLLO_MISSION_ENDPOINT_URI)
.then((client: AadHttpClient) => {
const endpoint: string = `${NASA_APOLLO_MISSION_ENDPOINT_URI}/api/nasa-apollo-missions`;
client.get(endpoint, AadHttpClient.configurations.v1)
.then((rawResponse: HttpClientResponse) => {
// verify successful response
if (rawResponse.status === 200) {
return rawResponse.json();
} else {
throw new Error('Error occurred when retrieving missions.');
}
})
.then((jsonResponse: IMission[]) => {
resolve(jsonResponse);
})
.catch((error) => {
reject(error);
});
});
});
}
}
@OliverZeiser said:
I think those ootb webparts are also getting a token for MS graph using the underlying adal infrastructure and interfering with the custom webparts.
All of that stuff uses the SPO infrastructure to get a token which today still uses ADAL, including our custom stuff. The plan is to move to MSAL JS but ETA is unknown at this time. But that will be transparent to us as that's handled by the SPFx API.
@andrewconnell The same thing happens with MSGraphClient. And for me it looks like a timing issue and as such it is quite hard to reproduce. But here is an example what happens in the session storage:
When everything is working fine, the session storage for ADAL looks like this. This is with just one custom webpart requesting a graph token.

When adding the document library webpart to the page and hitting F5 a couple of times (after clearing the session storage) I'll eventually end up with this (note the invalid_state here):
As you can see there are not two tokens, but just one, the one from the document library webpart. My custom webpart failed when getting the token. This can be the other way around as well. Thats why I am guessing it is a timing issue when multiple components request a token more or less at the same time.
What it should look like and also does look like when I add one webpart first, wait until it has a token and then add another webpart to the page without clearing session storage is this:
Again this is a hint for me that it is probably a timing issue.
I know that this is very hard to reproduce. In my case it was easier to reproduce when adding an extension that requests a token than a second webpart. Again I am guessing it is due to the fact of the loading order for the components and since it is beeing related to a timing issue. The more components you have on your page requesting differnt kinds of tokens, the easier it gets to reproduce it. Just make sure to clear the session storage all the time. Once you have a valid token things will be working fine for quite some time....