Automatically generate oauth tokens in Postman
Posted
Last updated
2 min read
Using Postman's own documentation you can manually obtain access tokens by filling in some information and perform a request, copy the access token and use it other requests that require a valid access token (as described here https://learning.postman.com/docs/sending-requests/authorization/#oauth-20). Or....
Use a pre-request script to generate an access token
In this tutorial I decided to do this on the collection level so that all requests that reside in this collection can inherit the auth settings and use the automatically generated access token.
Edit your Postman collection and add a pre-request script. This will ensure that the script will be executed for all of the requests that are under this collection.
Click the Pre-request script tab, and paste in the code (see below) and hit the save button in the top right corner.
Pre-request script:
1// Prepare http request
2const request = {
3 url: pm.environment.get('tokenUrl'),
4 method: 'POST',
5 body: {
6 mode: 'urlencoded',
7 urlencoded: [
8 {
9 key: "grant_type", value: pm.environment.get("grantType")
10 },
11 {
12 key: "client_id", value: pm.environment.get("clientId")
13 },
14 {
15 key: "client_secret", value: pm.environment.get("clientSecret")
16 },
17 ]
18 }
19}
20
21// Get the access token and set it as an environment variable in Postman
22pm.sendRequest(request, function (_, response) {
23 var jsonResponse = response.json();
24 var token = jsonResponse['access_token'];
25
26 // Set the token in the Postman environment variable to be used in the requests
27 pm.environment.set('accessToken', token);
28});
Create an environment in Postman
Create a new environment in Postman called DEVELOPMENT (or whatever) and add the following variables with the values you need for your oauth settings:
tokenUrl
grantType
clientId
clientSecret
accessToken
Set auth settings in the Postman collection
The last step here is to update the auth settings for the collection so that all the requests in there inherit the settings and can use the access token.
Go to the tab "Authorization" for your collection
Set Type to Bearer Token
Set the Token field to contain your variable, e.g.
{{accessToken}}
Success! 🎉🥳 All of your requests inside this collection will be now just work. They will use the access token that was obtained by the pre-request script.