@florian
This is an example using a pre-request script to login to Microsoft.
pm.test("Check for collectionVariables", function () {
let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
vars.forEach(function (item, index, array) {
console.log(item, index);
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.undefined;
pm.expect(pm.collectionVariables.get(item), item + " variable not set").to.not.be.empty;
});
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/v2.0/token',
method: 'POST',
header: 'Content-Type: application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: pm.collectionVariables.get("clientId"), disabled: false },
{ key: "scope", value: pm.collectionVariables.get("scope"), disabled: false },
{ key: "username", value: pm.collectionVariables.get("username"), disabled: false },
{ key: "password", value: pm.collectionVariables.get("password"), disabled: false },
{ key: "client_secret", value: pm.collectionVariables.get("clientSecret"), disabled: false },
{ key: "grant_type", value: "password", disabled: false },
]
}
}, function (err, res) {
if (err) {
console.log(err);
} else {
pm.test("Status code is 200", () => {
pm.expect(res).to.have.status(200);
});
let resJson = res.json();
pm.collectionVariables.set("bearerTokenExpiresOn", resJson.expires_in);
pm.collectionVariables.set("bearerToken", resJson.id_token);
}
});
}
});
However, looking at a few articles on the subject. Even though this works for me, itโs basically getting a new ID token each time. Itโs not using a refresh token. As Iโm not testing the login per se, this is ok for my circumstances. It might not be for yours.
If you really want it to replicate how an application should work, then the following resources may explain the differences.
Access token vs Refresh token in OAUTH2 | by Donald Le | Medium
AccessToken Vs ID Token Vs Refresh Token - What? Why?When? (c-sharpcorner.com)
OAuth 2.0 Refresh Token Best Practices (fusebit.io)
For this to work properly and mimic a real application, it looks like you should have something similar to the code I detailed above but with an if statement that requests a new token if the collection variable used to store the token is blank, but a slightly different sendRequest if requesting just a refresh token.
I canโt remember seeing any example of using refresh codes properly, when I originally set all this up for our purposes which was only a couple of months ago. All of the examples were getting a new access token each and every time.