Skip to content

Instantly share code, notes, and snippets.

@softius
Last active November 12, 2021 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save softius/9b5ad9763c26e5a0d02924d5b5450438 to your computer and use it in GitHub Desktop.
Save softius/9b5ad9763c26e5a0d02924d5b5450438 to your computer and use it in GitHub Desktop.
Automatic authentication in Postman
/**
* Ensures that we have a valid token before any request.
*
* To use this, you need to edit the Collection
* 1) select "Bearer Token" and provide `{{accessToken}}` as the Token, under Authorisation tab.
* 2) copy this script into "Pre-request scripts"
*
* Last, you need to define the following variables under the Environment
* baseUrl : API URL ie https://example.com/
* username: The username to connect with
* password: The password for the above username
*/
const tokenExists = pm.environment.get('accessToken') && pm.environment.get('expiresOn');
if (tokenExists) {
const tokenExpired = pm.environment.get('expiresOn') <= (new Date()).getTime() - 30;
if (tokenExpired) {
// Token expired so we are renewing
const refreshTokenRequest = {
url: pm.environment.get('baseUrl') + '/api/session/token',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify({
refresh_token: pm.environment.get('refreshToken')
})
}
};
pm.sendRequest(refreshTokenRequest, (error, response) => {
if (error !== null) {
console.log(error);
return;
}
const data = response.json();
const expiresOn = new Date();
expiresOn.setSeconds(expiresOn.getSeconds() + data.expires_in)
pm.environment.set('expiresOn', expiresOn.getTime());
pm.environment.set('accessToken', data.access_token);
});
}
} else {
// Token not found so we are creating a new session
const newTokenRequest = {
url: pm.environment.get('baseUrl') + '/api/token',
method: 'POST',
header: 'Content-Type:application/json',
body: {
mode: 'application/json',
raw: JSON.stringify({
username: pm.environment.get('username'),
password: pm.environment.get('password')
})
}
};
pm.sendRequest(newTokenRequest, (error, response) => {
if (error !== null) {
console.log(error);
return;
}
const data = response.json();
const expiresOn = new Date();
expiresOn.setSeconds(expiresOn.getSeconds() + data.expires_in)
pm.environment.set('expiresOn', expiresOn.getTime());
pm.environment.set('accessToken', data.access_token);
pm.environment.set('refreshToken', data.refresh_token);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment