Forked from jongio/azure-rest-apis-with-postman-pre-request-script.js
Created
July 13, 2021 14:36
-
-
Save manualbashing/ce93442fcc51b5f1ec3f2df28b8dedec to your computer and use it in GitHub Desktop.
Postman Collection Bearer Token Pre-Request Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!pm.collectionVariables.get("bearerToken") || Date.now() > new Date(pm.collectionVariables.get("bearerTokenExpiresOn") * 1000)) { | |
pm.sendRequest({ | |
url: 'https://login.microsoftonline.com/' + pm.collectionVariables.get("tenantId") + '/oauth2/token', | |
method: 'POST', | |
header: 'Content-Type: application/x-www-form-urlencoded', | |
body: { | |
mode: 'urlencoded', | |
urlencoded: [ | |
{ key: "grant_type", value: "client_credentials", disabled: false }, | |
{ key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false }, | |
{ key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false }, | |
{ key: "resource", value: pm.collectionVariables.get("resource") || "https://management.azure.com/", disabled: false } | |
] | |
} | |
}, function (err, res) { | |
if (err) { | |
console.log(err); | |
} else { | |
let resJson = res.json(); | |
pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_on); | |
pm.collectionVariables.set("bearerToken", resJson.access_token); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment