Automatically retrieve, store, refresh bearer token

Hi, I’m new to Postman and I cannot figure out how to store authentication for a collection. Here’s the API: User Deletion

Right now, I’m manually obtaining the auth_token and copy/pasting it into the auth tab of the deletion and status requests. The tokens expire every 5 mins, so I need to this frequently as I check the deletion request status.

Is there any way to obtain auth automatically and use it as the bearer token for subsequent requests? I’ve been able to do this for Basic Auth in another collection, but “Inherit from Parent” isn’t working in the case of Heap’s API.

Hi @usrnamesAreHard

You could get the request info from the API docs and then build it into a pre-req (so that it is called before every request), using something like this;

pm.sendRequest({
    url: 'https://postman-echo.com/post',
    method: 'POST',
    header: 'headername1:value1',
    body: {
        mode: 'raw',
        raw: JSON.stringify({ key: "this is json" })
    }
}, function (err, res) {
    console.log(res);
});

ref: Postman pm.sendRequest example · GitHub

1 Like

Here is what I use for this.

1 Like

Thanks, I’ll take a look!

Okay, so, I tried this and the auth request is returning Unauthorized, which breaks the script. I can’t figure out what’s wrong with the request:

POST /api/public/v0/auth_token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic [my_app_id]:[my_api_key]
User-Agent: PostmanRuntime/7.29.0
Postman-Token: [postman_token]
Host: heapanalytics.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: heap=[cookie_value]
Content-Length: 0

The same app_id and api_key work when done manually.

Did you base64 encode the app id and key?

The documentation doesn’t say it needs to be, but that said, I’ve tried encoding each, but same error.

Okay, I made the manual request that is/was working, checked the console log and just copy/pasted that encoded value…which worked. Not sure where my encoding was off, but either way, working now. Thanks again!