Last active
September 22, 2021 15:14
-
-
Save chris-kobrzak/f648b95526c783d79f0399937de30013 to your computer and use it in GitHub Desktop.
Postman pre-request script for automatic JWT-authentication. Please see config options at the top of the 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
// Environment variable names config | |
const env = { | |
ACCESS_TOKEN: '_token', // This env var will be created by the script | |
AUTH_TIME: '_authTime', // This env var will be created by the script | |
BASE_URL: 'baseUrl', | |
ID: 'username', | |
SECRET: 'password' | |
} | |
// API config | |
const api = { | |
PATH: '/users/login', | |
TOKEN_PROP: 'access_token', | |
requestBody: { | |
ID: 'username', | |
SECRET: 'password', | |
// In case your API requires additional, static properties | |
CUSTOM_FIELDS: [{key: 'custom_key', value: 'value'}] | |
} | |
} | |
const accessToken = pm.environment.get(env.ACCESS_TOKEN) | |
const latestAuthTime = pm.environment.get(env.AUTH_TIME) | |
const currentTime = new Date().getTime() | |
const tokenLifespanMs = 1000 * 60 * 60 // 1 hour | |
if (accessToken && (currentTime - latestAuthTime < tokenLifespanMs)) { | |
return | |
} | |
const url = pm.environment.get(env.BASE_URL) + api.PATH | |
const id = pm.environment.get(env.ID) // or pm.globals... if you have the same creds in all envs | |
const secret = pm.environment.get(env.SECRET) | |
const tokenRequest = { | |
method: 'POST', | |
url, | |
body: { | |
mode: 'urlencoded', | |
urlencoded: [ | |
{key: api.requestBody.ID, value: id, disabled: false}, | |
{key: api.requestBody.SECRET, value: secret, disabled: false}, | |
...api.requestBody.CUSTOM_FIELDS | |
] | |
} | |
} | |
pm.sendRequest(tokenRequest, (error, response) => { | |
const jsonResponse = response.json() | |
const newAccessToken = jsonResponse[api.TOKEN_PROP] | |
if (!newAccessToken) { | |
pm.environment.unset(authTimeProp) | |
return | |
} | |
pm.environment.set(env.ACCESS_TOKEN, newAccessToken) | |
pm.environment.set(env.AUTH_TIME, currentTime) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment