Does Postman Interceptor sync bearer tokens?

I’m not very knowledgeable on how bearer tokens work, so please correct me if this is not a real issue with Postman.

At the moment, I can use the Interceptor to sync up cookies fine on one project that I’m working on (does not use bearer). I log in manually in Chrome and then any postman requests will work from there.

For a different project, it uses bearer tokens. I log in but it doesn’t automatically sync it and I don’t know why. I have to copy and paste the bearer token into request header in order for it to work. There is nothing unusual about the prefix for this bearer token, it just starts with ‘Bearer’ following by a long string. Should the Interceptor be able to handle this or do I have to do a pre-request script to set it?

If you do need to set a pre-request script, I did try to create one based on another forum post by changing it slightly. I needed to make it send a request with raw text body (login) then set a variable. However it didn’t quite work, I don’t remember why but when I will update this post when I can get the error message.

var tokenRequest = {
    url: pm.environment.get("url") + '/token', 
    method: 'POST',
    header: {
        'Content-Type':'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'raw',
        raw: 'grant_type=password&username=username&password=password'
    }
  };

// send bearer token request
pm.sendRequest(tokenRequest, function (err, response) {
    if (err) {
        throw err;
    }
    if (response.code !== 200) {
        throw new Error('Could not log in.');
    }
    pm.environment.set("bearerToken", response.json().access_token);
});

Looking at it now, I think the issue may be the last bit where it says response.json. It’s not json but plain text so what should it be instead?

Thanks for your help in advance.

Hey @phil7

Welcome to the community! :star:

You should be able to use response.text() - can you share a screenshot of the error you’re seeing?

The body doesn’t look quite right to me though, given the header that you’re using.

Do you have an example of the full login request that not in a script? A Curl request for example, you could use that to figure the correct syntax for the script.

Thanks @dannydainton, judging from your comment I assume that the solution is indeed a pre-request script then? It’s outside the scope of the interceptor?

I think I got it wrong actually, I should keep response.json() because the response returned was actually in JSON format. I confused that with my request body sorry, so I didn’t need response.text() in the end. It’s all sorted now, thanks for your help. The issue was actually with me setting the environment variables wrong in the end.