Created
February 28, 2021 22:43
-
-
Save jongio/3a5b543407577ba61a83ee74fedb88cd to your computer and use it in GitHub Desktop.
Postman Collection Bearer Token Pre-Request Script
This file contains 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