top of page
Search
  • Writer's pictureJK

Configuring OAuth 2.0 Token Retrieval with Pre-request Scripts in Postman

Introduction


Postman is a widely-used tool for API testing and development. One of the critical parts of API testing is authentication and authorization. OAuth 2.0 is a standard protocol for authorization, and Postman provides built-in support for automating its workflow. In this blog post, we'll cover how to configure Postman to automatically retrieve an OAuth 2.0 token before sending an API request.


Prerequisites

- Basic understanding of OAuth 2.0

- Postman installed on your machine

- Access to an API that uses OAuth 2.0 for authorization


Steps


Step 1: Setup Environment Variables


  1. Open Postman and go to your API Collection.

  2. Click on "Manage Environments" (gear icon on the top right corner).

  3. Create a new environment (let's call it "OAuthEnv").

  4. Add variables: `tokenUrl`, `clientId`, `clientSecret`.

These variables hold your OAuth 2.0 configuration settings.


Step 2: Write Pre-request Script


Go to the API request where you need the OAuth token. In the "Pre-request Script" tab, add the following code:




function getvar(variableName) {  
    let value = pm.variables.get(variableName);  
    if (!value) throw new Error(  
        `Variable '${variableName}' is not defined. Did you forget to select an environment?`);  
    return value;  
}  
let tokenUrl = getvar('tokenUrl');  
let clientId = getvar('clientId');  
let clientSecret = getvar('clientSecret');    
let getTokenRequest = {  
    method: 'POST',  
    url: tokenUrl,  
    auth: {  
        type: "basic",  
        basic: [  
            { key: "username", value: clientId },  
            { key: "password", value: clientSecret }  
        ]  
    },  
    body: {  
        mode: 'formdata',  
        formdata: [  
            { key: 'grant_type', value: 'client_credentials' },  
        ]  
    }  
};  
  
pm.sendRequest(getTokenRequest, (err, response) => {  
    let jsonResponse = response.json(),  
        newAccessToken = jsonResponse.access_token;  
    pm.environment.set('accessToken', newAccessToken);  
    pm.variables.set('accessToken', newAccessToken);  
});

Step 3: Utilize the Token in Your API Requests


You can now access the freshly set accessToken from the environment or global variables. To use this token in your API requests, you can add a header like this:


Authorization: Bearer {{accessToken}}

Here, `{{accessToken}}` is the variable syntax to fetch the `accessToken` from the environment variables.



Conclusion


Automating OAuth 2.0 token retrieval using Postman’s Pre-request scripts can streamline your API testing process and make it more robust. This guide covered how to fetch an OAuth 2.0 token using the Client Credentials Grant type. Similar methods can be used for other grant types as well.



41 views0 comments

Recent Posts

See All
bottom of page