I'm currently working on developing a function in Office Scripts to obtain an OAuth API token. I have a functional example of making a token request in PowerShell and attempted to replicate the same process using fetch
in Office Scripts, but unfortunately, I am encountering a failed to fetch
error within Office Scripts.
The PowerShell function below effectively retrieves a token:
#requires -Version 3.0
function New-ApiAccessToken
{
param
(
[string]$apiUrl,
[string]$apiKey,
[string]$apiSecretKey
)
# Specify security protocols
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
# Convert password to secure string
$securePassword = ConvertTo-SecureString -String 'public' -AsPlainText -Force
# Define parameters for Invoke-WebRequest cmdlet
$params = @{
Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ('public-client', $securePassword)
Uri = '{0}/auth/oauth/token' -f $apiUrl
Method = 'POST'
ContentType = 'application/x-www-form-urlencoded'
Body = 'grant_type=password&username={0}&password={1}' -f $apiKey, $apiSecretKey
}
# Request access token
try {(Invoke-WebRequest @params | ConvertFrom-Json).access_token}
catch {$_.Exception}
}
# Define parameters
$params = @{
apiUrl = 'myurlhere'
apiKey = 'thekey'
apiSecretKey = 'thesecretkey'
}
# Call New-ApiAccessToken function using defined parameters
New-ApiAccessToken @params
The script provided below in Excel/Office Scripts returns a failed to fetch
error on the fetch line:
async function getToken() {
let url = 'myurlhere';
let client_id = 'public-client';
let client_secret = 'public';
let username = 'thekey';
let password = 'thesecretkey';
let basicAuth: string = base64Encode(client_id + ":" + client_secret).toString();
let bodyParams: URLSearchParams = new URLSearchParams();
bodyParams['grant_type'] = 'password';
bodyParams['username'] = username;
bodyParams['password'] = password;
let response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json; charset=UTF-8',
'Authorization': 'Basic ' + basicAuth
},
body: bodyParams
});
let token: string = await response.json();
console.log(token)
}
Upon monitoring the requests with Fiddler (with Decrypt HTTPS traffic enabled):
- The PowerShell script displays 2 POST calls; The first returns response code 401, while the second successfully obtains the token with response code 200
- The Office script only shows one OPTIONS call which returns response code 401; There is no second call observed
How can I modify the Office script to effectively retrieve the token?