2

Automatic authorization in Postman

 2 years ago
source link: https://dev.to/iacons/automatic-authorization-in-postman-34dk
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Working with short lived JWTs can be painful when you don't have an automated mechanism in place to refresh the token. This is quite common when setting up a new collection in Postman.

In this post we will be looking on how we can automate this, so that we retrieve, refresh and use the token right before each API call.

Environment configuration

Before we get started, we need to define a few environment variables in Postman. These are:

  • baseUrl API URL
  • username The username to connect with
  • password The password for the above username

Unfortunately, there's no way to display the password as a ... password field. Postman will store and display everything in clear text, so have that in mind.

Pre-request script

Then, we need to edit the collection and configure the Pre-request script code. To do that, right click on the collection, select edit and then "Pre-request scripts"

Here is an example. As you can see the implementation is quite generic so most likely you will need to adjust a few things to make that work for you.

/** * 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); }); }

How it works

Initially we check whether we have a token stored. If not we go ahead and retrieve a new one along with expiration time.

We store both in environment variables. You don't need to create these variables, the script will create them whenever necessary.

If the token exists, we check also whether it has expired. In that case, we refresh the token and similarly to above we store the new token and its expiry date.

In either case, the token will be stored in a new environment variable called accessToken. This can be used to define the default authorization method. To do this right click on the collection, select edit, then Authorisation and use the variable {{accessToken}}.

Conclusion

I hope you find this approach useful and hopefully it will save you from some time from manual actions.

Make sure to follow me on dev.to, Medium or Twitter to read more about PHP, Docker and other dev topics.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK