Is it possible to add a Bearer Token auth type in the pm.sendRequest function?

In the Pre-request script, is it possible to add a Bearer Style authentication in the pm.sendRequest function? If so, what does the syntax look like?

pm.sendRequest({
            url: "URL of some type", 
            method: 'POST',
            auth: {
                 type:'bearer',
                 token: 'Bearer Token'
            }
            header: {
                'Content-Type': 'application/xml'
            },
            body: {
                mode: 'raw',
                raw: `Body Data of some type`
            }
        }, function (err, res) {
            if(err) {
                throw new Error(err);
            } else {
                console.log("auth was successful")
            }
});
1 Like

You add a number of different things into .sendRequest().

Iā€™m not sure of the full context of the actual request your making but there are some different examples in this gist which I always find useful.

Itā€™s a pre-request script that requires Bearer Token authorization for the requests in it. I already have the token, I just need to pass it into a request like what I listed as an example.
I already know how to do a basic auth with similar syntax. My issue is around what the syntax for a bearer style authentication.

 // Authentication
pm.sendRequest({
        url: 'https://test.com',
        method: 'POST',
        auth: {
                 type: "basic",
                 basic: [
                      {key: "username", value:"user"},
                      {key: "password", value:"password"}
            ]
        },
        body: {
            mode: 'urlencoded',
            urlencoded: [
                {key: "Content-Type", value: "application/x-www-form-urlencoded", disabled: false},
                {key: "grant_type", value: "client_credentials", disabled: false}
            ]
        }
}, function (err, res) {
        if(err) {            
throw new Error("An error occurred during authentication, please review:\n" + JSON.stringify(err));
        } else {
            console.log(res.json());

            // Confirm the request was successful
            pm.expect(res).to.have.property('code', 200);
            let data = res.json();
            pm.environment.set("token", "Bearer " + data.access_token);
        }
});

My mistake, I thought you were trying to get one with that request :man_facepalming:

It looks like you already added the word Bearer when setting the variable so you would just need to add a new Authorization header with the value in the example.

pm.sendRequest({
    url: "URL of some type",
    method: 'POST',
    header: {
        'Authorization': `${pm.environment.get('token')}`,
        'Content-Type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: `Body Data of some type`
    }
}, function (err, res) {
    if (err) {
        throw new Error(err);
    } else {
        console.log("auth was successful")
    }
});

More information on Javascript template literals:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

I attempted this with my request and itā€™s still failing validation. It requires that I have the Bearer Authorization setup separately.

I would have thought that if you have the pre-request script thatā€™s getting the Bearer Token, wouldnā€™t you just use that token value in an Authorization Header of your normal requests.

I donā€™t really understand why youā€™re using this in another pre-request. I donā€™t know your context and what you have in front of you so that only think that I can offer is a ā€˜guessā€™.

Itā€™s due to some constraints that are being set from the BE due to code note present in the FE of the project. I believe once those constraints are removed, your solution should work with no issue

I found out how to do this type of auth in the pre-request script:

       pm.sendRequest({
        url: "some URL", 
        method: 'POST',
        auth: {
			type: "bearer",
			bearer: [
				{
					key: "token",
					value: "Bearer " + bearerToken,
					type: "string"
				}
			]
		},
        header: {
            'Content-Type': 'application/xml'
        },
        body: {
            mode: 'raw',
            raw: `type of body`
        }
    }, function (err, res) {
        if(err) {
            throw new Error(err);
        } else {
            console.log("auth was successful")
        }
    });
1 Like

I appreciate your help through this endeavour @danny-dainton, you gave me some really good references to read through that helped me out. You rock!

1 Like

Ha, I actually had it this way (minus the type property) in one of my initial responses but I edited the code after seeing your example :man_facepalming:

Totally up to you and down to personal preference but Iā€™m a fan of this syntax.

`Bearer ${bearerToken}`

To me, it feels more readable than:

"Bearer " + bearerToken 
1 Like

@Zachary: Great post!
It helped me to solve my problem.
However, when I first tried this I had an issue with the token.
Analysis of the ressonse headers revealed that the Bearer token was like this:
ā€˜Bearer Bearer llkjh876976jjhgjhg874653hgIjā€¦ā€™
The word ā€˜Bearerā€™ was used twice, hence the authentication was KO.
So I deleted the ā€œBearerā€ part of the ā€˜value:ā€™ assignment

bearer: [
{
key: ā€œtokenā€,
value: bearerToken,
type: ā€œstringā€
}
]

and it did work immediately for me.
Thanks

God blessed you with this response, after 2 hours of solving the problem its finally over thanks to your help. God blessed, alhamdulillah