Support for calling entra-authenticated external APIs
It is possible to call an external API via an Execute Script action containing the following;
!async function () {
const tokenProvider = await spfxContext.aadTokenProviderFactory.getTokenProvider();
const token = await tokenProvider.getToken('af111ed2-e4fb-4936-9c45-01f3be930545');
const headers = new Headers();
const bearer = `Bearer ${token}`;
headers.append('Authorization', bearer);
const options = {
method: 'GET',
headers: headers
};
const fetchResult = await fetch('https://localhost:44351/api/Settings', options);
const result = await fetchResult.json();
console.log(result);
}();
However, this is difficult to work with and I suggest the following:
- `spfxContext` should be available as a page context object. Right now it isn't recognised.
- The 'Send HTTP request' action could have support for generating token - simply add a "client id" field and it appends the "Authorization: bearer token" header to the request using code above.
- Support for async code in code blocks - we have to wrap async calls in an `async function () { }` block, but then the code is executed in the background after the action ends.
- It isn't possible to use the `Send HTTP request` action because of the async issue above since I can't create a variable for the auth token.
- I can't do anything with the result since the code block is ended.
Any short term workarounds that I can do to be able to process the API result would be helpful. I just want to be able to set a variable or something when the API returns.
Thanks!!
0
-
Just to follow up on this - after speaking to the team, if a Promise object is returned from the script action, it will be awaited and the promise result is used as the action output which is perfect.
Therefore, to use async calls, you can use this pattern:
let func = async function () {
const tokenProvider = await spfxContext.aadTokenProviderFactory.getTokenProvider();
const token = await tokenProvider.getToken('7c816beb-102f-49cd-88f7-06085e5df3ac');
const headers = new Headers();
const bearer = `Bearer ${token}`;
headers.append('Authorization', bearer);
headers.append('Accept', 'application/json, text/plain');
headers.append('Content-Type', 'application/json;charset=UTF-8');
const options = {
method: 'POST',
headers: headers,
body: JSON.stringify(...)
};
const result = await fetch('url', options);
return await result.json();
};
//Convert the async function call to a promise for Skybow to be able to interpret the result
return new Promise((resolve, reject) => {
func().then(result => {
resolve(result);
});
});Alternatively, just don't await the last async call of your method.0
Please sign in to leave a comment.
Comments
1 comment