Postman automated oAuth2 Client Credentials via Pre-request Script

At work I’m working on an API integration with Mautic and for quick API call testing I use, like many, Postman (the desktop app version). With the below steps you can automate the oAuth2 Client Credentials.

Step 1: Setup an Environment for Mautic

In this Mautic environment, create the following 3 variables:

  • base_url
  • oauth2_client_id
  • oauth2_client_secret

Populate them with the values. Be aware that the {{base_url}} is the URL of your Mautic installation without a trailing slash (/) or /api/ at the end.

For the client ID and secret, go to Mautic > Settings > API Credentials.
Create a set of client keys if you haven’t done so yet.

Step 2: Select the Environment

Select the Mautic environment you just created in the dropdown at the top right corner of the app.

Step 3: Open the collection > Authorization tab

Now go to the Authorization tab of your collection and:

  • Set the Type to Bearer Token.
  • Add {{mautic_bearer_token}} as the value for Token.

Step 4: Open the collection > Pre-request Script tab

Copy the below code and paste it the tab.

// oAuth2, Client Credentials, no user impersonation so no manual login required
// source: https://forum.mautic.org/t/postman-automated-oauth2-client-credentials-via-pre-request-script/25192
// author: stgoos
// tested with: Mautic 4.4.x
pm.sendRequest({ 
    url: pm.environment.get("base_url") + "/oauth/v2/token",
    method: 'POST',
    header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            {key: 'client_id', value: pm.environment.get("oauth2_client_id")},
            {key: 'client_secret', value: pm.environment.get("oauth2_client_secret")},
            {key: 'grant_type', value: 'client_credentials'}
        ]
    }
},
    (err, res) => {
        pm.globals.set("mautic_bearer_token", res.json().access_token)
        // or use pm.environment.set() instead when you want to store the token in the active environment
        // console.log(res.json());
});

Step 5: you’re (almost) done

Well, basically you’re done, just don’t forget to set the Authorization Type of your requests to Inherit auth from parent (if it wasn’t set to that already).

Enjoy your automated collection and apply of the Bearer token with every request.