# Setting headers for entire collection/folder

**URL:** <https://community.postman.com/t/setting-headers-for-entire-collection-folder/708>\
**Category:** Help Hub\
**Tags:** scripts, headers\
**Created:** [January 18, 2018, 10:02am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708 "2018-01-18T10:02:47Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![singhsivcan](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/singhsivcan/32/1595_2.png) [@singhsivcan](https://community.postman.com/u/singhsivcan)\
**Post date:** [May 7, 2019, 8:44am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/21 "2019-05-07T08:44:39Z")

</div>

Can you open Postman Console and check?  
View \> Show Postman Console or you can click the following icon:  
 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/f/fdf5fa119222c53a3d39f3c6ea48d3616ff43a57.png)

Now, once you send the request you’ll see what all headers are actually going through along with your request like so:

 ![image](https://us1.discourse-cdn.com/getpostman/original/3X/4/5/45eddb7dcb6b03ece126abf05d409d8044359eff.png)

Also,  
The headers that are dynamically generated through the pre-request script will not be shown up as a part of the code that is generated.

---

<div class="post-metadata">

**Author:** ![lutaiphong](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/lutaiphong/32/1759_2.png) [@lutaiphong](https://community.postman.com/u/lutaiphong)\
**Post date:** [May 7, 2019, 10:25am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/22 "2019-05-07T10:25:52Z")

</div>

YAHOO!  
It worked guys.

 ![16](https://us1.discourse-cdn.com/getpostman/original/3X/6/9/69f4d1d7bba64146cc5ba93a0c75498620db9537.png)

Maybe I got mixed something earlier.

Thanks a lot.  
Super cool support.

---

<div class="post-metadata">

**Author:** ![carivaldi](https://avatars.discourse-cdn.com/v4/letter/c/74df32/32.png) [@carivaldi](https://community.postman.com/u/carivaldi)\
**Post date:** [May 14, 2019, 11:11am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/23 "2019-05-14T11:11:20Z")

</div>

Unfortunately still does not work for me (Postman 6.7.1, linux-4.15.0-48-generic on x64 / Ubuntu 18.04). At the level of pre-request script the additional header is successfully added to the headers collection, however it is somehow lost in the final, sent request. Which would be actually coherent with what the [documentation says about request object](https://learning.getpostman.com/docs/postman/scripts/postman_sandbox#requestresponse-related-properties):

> This object is read-only. Changing properties of this object will have no effect.

Has something changed in the implementation recently?

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [May 14, 2019, 11:39am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/24 "2019-05-14T11:39:32Z")

</div>

Hey @carivaldi,

> [@Setting headers for entire collection/folder](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/14):
>
> As of 7.0.9 - You should be able to now do this in your Pre-request Scripts. You can use the following syntax: pm.request.headers.add({key: 'header\_name', value: 'header\_value' }) pm.request.headers.upsert({key: 'header\_name', value: 'header\_value' }) pm.request.headers.remove('header\_name') EDIT: Fork this collection to see how it works directly in Postman: [https://www.postman.com/postman/workspace/postman-answers/collection/9215231-ef055751-7385-45b4-a6f9-91bbd1c47fa5?ctx=documentation](https://www.postman.com/postman/workspace/postman-answers/collection/9215231-ef055751-7385-45b4-a6f9-91bbd1c47fa5?ctx=documentation)

I can see from your message that you have 6.7.1.

We’re going through the documentation and updating this to reflect the current functionality - This will eventually be shown here:

> **[Process data and script workflows using Postman JavaScript objects | Postman...](https://learning.postman.com/docs/tests-and-scripts/write-scripts/postman-sandbox-api-reference/)**
>
> Postman is a collaboration platform for API development. Postman's features simplify each step of building an API and streamline collaboration so you can create better APIs—faster.

---

<div class="post-metadata">

**Author:** ![carivaldi](https://avatars.discourse-cdn.com/v4/letter/c/74df32/32.png) [@carivaldi](https://community.postman.com/u/carivaldi)\
**Post date:** [May 14, 2019, 12:31pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/25 "2019-05-14T12:31:59Z")

</div>

@danny-dainton thanks for the quick response!  
I can see the Ubuntu repository is a a little bit behind - I’ll try again when 7.0.9 is there.

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [May 14, 2019, 1:04pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/26 "2019-05-14T13:04:00Z")

</div>

Which method of installation of you using? If you’re using [snap](https://snapcraft.io/postman) - You might need to use the `candidate` channel.

```
sudo snap switch --channel=candidate postman
sudo snap refresh postman
```

---

<div class="post-metadata">

**Author:** ![carivaldi](https://avatars.discourse-cdn.com/v4/letter/c/74df32/32.png) [@carivaldi](https://community.postman.com/u/carivaldi)\
**Post date:** [May 16, 2019, 7:39am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/27 "2019-05-16T07:39:05Z")

</div>

There is still 7.0.7 in the `candidate` channel - I switched to it and since it is not really a show stopper for me, I’ll wait patiently until 7.0.9 comes 🙂

Thanks for help!

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [May 28, 2019, 12:39pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/28 "2019-05-28T12:39:54Z")

</div>

Hey @carivaldi,

The [snap](https://snapcraft.io/postman) candidate channel has been updated to 7.1.1 - If you wanted to give the `headers` another go. 🙂

---

<div class="post-metadata">

**Author:** ![antares.mips](https://avatars.discourse-cdn.com/v4/letter/a/3e96dc/32.png) [@antares.mips](https://community.postman.com/u/antares.mips)\
**Post date:** [December 31, 2019, 7:52am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/29 "2019-12-31T07:52:47Z")

</div>

Thank you so match!!

---

<div class="post-metadata">

**Author:** ![matheusGuimaraes](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/matheusguimaraes/32/3555_2.png) [@matheusGuimaraes](https://community.postman.com/u/matheusGuimaraes)\
**Post date:** [January 10, 2020, 9:53am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/30 "2020-01-10T09:53:13Z")

</div>

hi guys,

I’m trying to add a header for every request under a folder. The pre-request scripts seem to be my best bet, however, I can’t get it to work with variables. It fails with bad syntax no matter which way I code it and I can’t find any documentation or thread on it.

Essentially, I need to read the values set in the environment variable since the header name and value depends on which environment you’re sending the request from.

So something like this:

pm.request.headers.add( { key: {{headerName}}, value: {{apiKey}} } );

That’s not valid syntax though. So how can I achieve this?

thanks! 🙂

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [January 10, 2020, 10:38am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/31 "2020-01-10T10:38:11Z")

</div>

Hey @matheusGuimaraes

Have you tried this:

`pm.request.headers.add( { key: pm.environment.get('headerName'), value: pm.environment.get('apiKey') } );`

---

<div class="post-metadata">

**Author:** ![matheusGuimaraes](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/matheusguimaraes/32/3555_2.png) [@matheusGuimaraes](https://community.postman.com/u/matheusGuimaraes)\
**Post date:** [January 10, 2020, 11:42am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/32 "2020-01-10T11:42:53Z")

</div>

Thank you, Danny!

I actually had tried that and it had failed with a syntax error, but I just tried again blindly with copy/paste from your reply and it worked so I must have missed a bracket or something and assumed it was lack of support for variables.

thank you so much and sorry for the time waste 🙂

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [January 10, 2020, 11:46am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/33 "2020-01-10T11:46:19Z")

</div>

You’re welcome. Glad to see you got it working. Don’t worry, it’s never a waste of anyones time. 🏆

---

<div class="post-metadata">

**Author:** ![ohjimijimijimi](https://avatars.discourse-cdn.com/v4/letter/o/43a26b/32.png) [@ohjimijimijimi](https://community.postman.com/u/ohjimijimijimi)\
**Post date:** [April 9, 2020, 2:16pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/34 "2020-04-09T14:16:15Z")

</div>

Hi,

Thanks to this post I manage to set a default header to a collection.

 ![image](https://us1.discourse-cdn.com/getpostman/original/2X/b/b6f92df086da2dbc2f22dfa84ac28b9a7eda801d.png)  
That’s great but, while it works and the request is sent correctly, it should be considered a workaround (or a bug to be fixed) because headers set this way are:

- not visualised in the headers list  
 ![screenshot-postman-2](https://us1.discourse-cdn.com/getpostman/original/2X/f/fad2b2c48a8fc5a788c92c79277847dfdb7ab399.png)
- not used when you export the request  
 ![screenshot-postman-3](https://us1.discourse-cdn.com/getpostman/original/3X/1/0/10c8e61280e23ebf1b9d287dfd32a36aa672aa1d.png)

What do you think?

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [April 9, 2020, 3:20pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/35 "2020-04-09T15:20:04Z")

</div>

Hey @ohjimijimijimi,

Welcome to the community! 🏆

I would expect to see that header in the Postman Console under the `Request Headers` and not in the request list that you would see.

Also, I wouldn’t expect to see it in the code snippet as that’s not taking anything in the `Pre-request Script` as that would of been actioned at runtime.

It looks like your app is slightly behind the current version as the temp headers section has been removed / changed now. 🙂

---

<div class="post-metadata">

**Author:** ![ohjimijimijimi](https://avatars.discourse-cdn.com/v4/letter/o/43a26b/32.png) [@ohjimijimijimi](https://community.postman.com/u/ohjimijimijimi)\
**Post date:** [April 9, 2020, 3:34pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/36 "2020-04-09T15:34:45Z")

</div>

Hey @danny-dainton,

thanks for the prompt response. You’re right, app was old, now is updated.

This is what I’m seeing in the temp headers section

 ![image](https://us1.discourse-cdn.com/getpostman/original/3X/3/3/332846c6acd0d8d11dc3aa8ec8d8220558afaa41.png)

I agree with you when you say

> I wouldn’t expect to see it in the code snippet as that’s not taking anything in the `Pre-request Script` as that would of been actioned at runtime.

Using the pre-script to add headers is maybe not the right approach, but to me it seems also the only one atm.

Is there any plan to add default headers per collection?

---

<div class="post-metadata">

**Author:** ![danny-dainton](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/danny-dainton/32/29401_2.png) [@danny-dainton](https://community.postman.com/u/danny-dainton)\
**Post date:** [April 9, 2020, 3:54pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/37 "2020-04-09T15:54:36Z")

</div>

There is a similar open feature request for this on our Github Tracker, you could upvote this so we’re aware more users would like to see this in the product 🙂

> <https://github.com/postmanlabs/postman-app-support/issues/8179>
>
> \<!--
> Please read through the \[guidelines\](https://github.com/postmanlabs/postma…n-app-support#guidelines-for-reporting-issues) before creating a new issue.
> \--\>
> 
> \*\*Is your feature request related to a problem? Please describe.\*\*
> I have to send some headers along with every request in a collection.
> Currently i've found no other way than setting them with the "pre-request script".
> 
> \*\*Describe the solution you'd like\*\*
> It would be easier to have a "headers" tab in the "Edit collection" dialog.
> This tab would have the same content as each request "headers" tab.
> 
> \*\*Describe alternatives you've considered\*\*
> The only alternative is stickying to the pre request script (which was introduced also for the same purpose, i see: https://github.com/postmanlabs/postman-app-support/issues/2955 )
> 
> \*\*Additional context\*\*
> Screenshot of where i'd add the headers tab, and what i'm currently doing.
> 
> !\[image\](https://user-images.githubusercontent.com/18366087/78938843-41ce5f80-7ab3-11ea-8fc8-8499b8791916.png)

---

<div class="post-metadata">

**Author:** ![qlodhi](https://avatars.discourse-cdn.com/v4/letter/q/67e7ee/32.png) [@qlodhi](https://community.postman.com/u/qlodhi)\
**Post date:** [August 12, 2020, 6:51pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/38 "2020-08-12T18:51:04Z")

</div>

The problem I faced with the selected answer is that it doesn’t copy/paste automatically the pre-request scripts in a new request even if you duplicate a request.  
The instructions in “Inheriting Auth” worked nicely though [https://learning.postman.com/docs/sending-requests/authorization/#inheriting-auth](https://learning.postman.com/docs/sending-requests/authorization/#inheriting-auth). I set Authorization to API Key, select a custom header key and set the value to an env variable `authToken` and choose “Inherit from Parent” for first request and when I duplicate this, the auth works out-of-the-box for new request. And if auth token changes, just update the env variable authToken and it should reflect for all requests without doing much.

---

<div class="post-metadata">

**Author:** ![knychtell](https://avatars.discourse-cdn.com/v4/letter/k/edb3f5/32.png) [@knychtell](https://community.postman.com/u/knychtell)\
**Post date:** [October 2, 2020, 11:41am UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/39 "2020-10-02T11:41:43Z")

</div>

@danny-dainton I hope all is well

I am just learning Postman and would like to be able to re-use the header value (set-Cookie) on my login call’s response header.

I am using REST API Calls:

1. POST [https://local:1234/e/api/keylogin/apikeylogin](https://local:1234/e/api/keylogin/apikeylogin)  
Within the request body, i declared my APIKey ID and Key Secret.  
If i hit send, The RESPONSE will be 200 status, if go to RESPONSE HEADERS it will create a cookie:  
Key Value  
Set-Cookie asc\_session\_id=xxxxx

I set this on the TEST of the REQUEST POST:

1. POST- [https://local:1234/e/api/folders/create](https://local:1234/e/api/folders/create)  
requeirement: Reuse the value of Set-Cookie  
and create a new header called asc\_xsrf\_token and pass the value of the first POST call(asc\_session\_id=xxxxx).

I basically would want to reuse the asc\_xsrf\_token on all my REST API Calls for this collection.  
I tried following your video but somehow i am getting syntax error

I tried to follow the solutions in the thread above but not able to accomplish the results.

Basically, i like to:

1. be able to create a new header on my create folder call named: asc\_xsrf\_token and pass the value from the asc\_session\_id from the Key= Set-cookie on my login request’s Response header.

2. Once the Header ( asc\_xsrf\_token) is created on the 2nd call( POST/ create folder), i will do the same thing for the rest of the REST API Calls.

Thank you in advance!  
Knychtell

---

<div class="post-metadata">

**Author:** ![cpeterson](https://avatars.discourse-cdn.com/v4/letter/c/58f4c7/32.png) [@cpeterson](https://community.postman.com/u/cpeterson)\
**Post date:** [November 4, 2020, 10:51pm UTC](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708/40 "2020-11-04T22:51:17Z")

</div>

This works for any calls I am making - shared from friend of friend, not sure the original source!  
This allows for variables in the path as well… `{{url}}/api/pms/hk/clean-types/{{type_id}}`

Just add this to the Pre-request Script on the folder and setup the environment variable described in the top comment.

```
    /*
     * HTTP-HMAC-POSTMAN
     * VERSION: 1.1.4
     *
     * To use this script, paste it into the Postman pre-script editor
     * - auto adds headers to the request.
     *
     * This code expects these Postman environment variables to be set:
     * {{env_pubkey}} defaults to ''
     * {{env_secretkey}} defaults to ''
     * {{env_realm}} defaults to 'Acquia'
     * {{secretIsBase64encoded}} defaults to true
     *
     * Note: Only HMAC version 2.0 is supported
     */
    
    var publicKey = pm.environment.get('env_pubkey') || '';
    var secretKey = pm.environment.get('env_secretkey') || '';
    var hmacRealm = pm.environment.get('env_realm') || 'Acquia';
    
    // Decide what to do with the secret
    var hasAlreadyEncodedSecret = pm.environment.get('secretIsBase64encoded') || true;
    
    
    //############################################################################
    //############################################################################
    //####################### DO NOT EDIT BELOW THIS POINT #######################
    //############################################################################
    //############################################################################
    
    if (hasAlreadyEncodedSecret && hasAlreadyEncodedSecret !== "false")
    {
        // do nothing here
    }
    else
    {
        // encode the secret
        // strictly, pre-encoding is incorrect but that is a discussion for another day
        wordArray = CryptoJS.enc.Utf8.parse(secretKey);
        secretKey = CryptoJS.enc.Base64.stringify(wordArray);
    }
    
    //Acquia HMAC LIB
    var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
    
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
    
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    
    if (!Date.now) {
        Date.now = function () {
            return new Date().getTime();
        };
    }
    if (!Object.keys) {
        Object.keys = function () {
            'use strict';
    
            var hasOwnProperty = Object.prototype.hasOwnProperty,
                hasDontEnumBug = !{ toString: null }.propertyIsEnumerable('toString'),
                dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'],
                dontEnumsLength = dontEnums.length;
    
            return function (obj) {
                if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' && (typeof obj !== 'function' || obj === null)) {
                    throw new TypeError('Object.keys called on non-object');
                }
    
                var result = [],
                    prop,
                    i;
    
                for (prop in obj) {
                    if (hasOwnProperty.call(obj, prop)) {
                        result.push(prop);
                    }
                }
    
                if (hasDontEnumBug) {
                    for (i = 0; i < dontEnumsLength; i++) {
                        if (hasOwnProperty.call(obj, dontEnums[i])) {
                            result.push(dontEnums[i]);
                        }
                    }
                }
                return result;
            };
        }();
    }
    if (!Array.prototype.forEach) {
        Array.prototype.forEach = function (callback, thisArg) {
            var T, k;
    
            if (this === null) {
                throw new TypeError(' this is null or not defined');
            }
    
            // 1. Let O be the result of calling toObject() passing the
            // |this| value as the argument.
            var O = Object(this);
    
            // 2. Let lenValue be the result of calling the Get() internal
            // method of O with the argument "length".
            // 3. Let len be toUint32(lenValue).
            var len = O.length >>> 0;
    
            // 4. If isCallable(callback) is false, throw a TypeError exception.
            // See: http://es5.github.com/#x9.11
            if (typeof callback !== "function") {
                throw new TypeError(callback + ' is not a function');
            }
    
            // 5. If thisArg was supplied, let T be thisArg; else let
            // T be undefined.
            if (arguments.length > 1) {
                T = thisArg;
            }
    
            // 6. Let k be 0
            k = 0;
    
            // 7. Repeat, while k < len
            while (k < len) {
                var kValue;
    
                // a. Let Pk be ToString(k).
                // This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the HasProperty
                // internal method of O with argument Pk.
                // This step can be combined with c
                // c. If kPresent is true, then
                if (k in O) {
                    // i. Let kValue be the result of calling the Get internal
                    // method of O with argument Pk.
                    kValue = O[k];
    
                    // ii. Call the Call internal method of callback with T as
                    // the this value and argument list containing kValue, k, and O.
                    callback.call(T, kValue, k, O);
                }
                // d. Increase k by 1.
                k++;
            }
            // 8. return undefined
        };
    }
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (searchElement, fromIndex) {
    
            var k;
    
            // 1. Let o be the result of calling ToObject passing
            // the this value as the argument.
            if (this === null) {
                throw new TypeError('"this" is null or not defined');
            }
    
            var o = Object(this);
    
            // 2. Let lenValue be the result of calling the Get
            // internal method of o with the argument "length".
            // 3. Let len be ToUint32(lenValue).
            var len = o.length >>> 0;
    
            // 4. If len is 0, return -1.
            if (len === 0) {
                return -1;
            }
    
            // 5. If argument fromIndex was passed let n be
            // ToInteger(fromIndex); else let n be 0.
            var n = +fromIndex || 0;
    
            if (Math.abs(n) === Infinity) {
                n = 0;
            }
    
            // 6. If n >= len, return -1.
            if (n >= len) {
                return -1;
            }
    
            // 7. If n >= 0, then Let k be n.
            // 8. Else, n<0, Let k be len - abs(n).
            // If k is less than 0, then let k be 0.
            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    
            // 9. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ToString(k).
                // This is implicit for LHS operands of the in operator
                // b. Let kPresent be the result of calling the
                // HasProperty internal method of o with argument Pk.
                // This step can be combined with c
                // c. If kPresent is true, then
                // i. Let elementK be the result of calling the Get
                // internal method of o with the argument ToString(k).
                // ii. Let same be the result of applying the
                // Strict Equality Comparison Algorithm to
                // searchElement and elementK.
                // iii. If same is true, return k.
                if (k in o && o[k] === searchElement) {
                    return k;
                }
                k++;
            }
            return -1;
        };
    }
    
    /**
     * AcquiaHttpHmac - Let's you sign a XMLHttpRequest or promised-based request object (e.g. jqXHR) by Acquia's
     * HTTP HMAC Spec
     */
    
    var AcquiaHttpHmac = function () {
        /**
         * Constructor.
         *
         * @constructor
         * @param {string} realm
         * The provider.
         * @param {string} public_key
         * Public key.
         * @param {string} secret_key
         * Secret key.
         * @param {string} version
         * Authenticator version.
         * @param {string} default_content_type
         * Default content type of all signings (other than specified during signing).
         */
        function AcquiaHttpHmac(_ref) {
            var realm = _ref.realm,
                public_key = _ref.public_key,
                secret_key = _ref.secret_key,
                _ref$version = _ref.version,
                version = _ref$version === undefined ? '2.0' : _ref$version,
                _ref$default_content_ = _ref.default_content_type,
                default_content_type = _ref$default_content_ === undefined ? 'application/json' : _ref$default_content_;
    
            _classCallCheck(this, AcquiaHttpHmac);
    
            if (!realm) {
                throw new Error('The "realm" must not be empty.');
            }
            if (!public_key) {
                throw new Error('The "public_key" must not be empty.');
            }
            if (!secret_key) {
                throw new Error('The "secret_key" must not be empty.');
            }
            var supported_versions = ['2.0'];
            if (supported_versions.indexOf(version) < 0) {
                throw new Error('The version must be "' + supported_versions.join('" or "') + '". Version "' + version + '" is not supported.');
            }
    
            this.config = {
                realm: realm,
                public_key: public_key,
                parsed_secret_key: CryptoJS.enc.Base64.parse(secret_key),
                version: version,
                default_content_type: default_content_type
            };
    
            /**
             * Supported methods. Other HTTP methods through XMLHttpRequest are not supported by modern browsers due to insecurity.
             *
             * @type array
             */
            this.SUPPORTED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'CUSTOM'];
        }
    
        /**
         * Check if the request is a XMLHttpRequest.
         *
         * @param {(XMLHttpRequest|Object)} request
         * The request to be signed, which can be a XMLHttpRequest or a promise-based request Object (e.g. jqXHR).
         * @returns {boolean}
         * TRUE if the request is a XMLHttpRequest; FALSE otherwise.
         */
    
    
        _createClass(AcquiaHttpHmac, [{
            key: 'sign',
    
    
            /**
             * Sign the request using provided parameters.
             *
             * @param {(XMLHttpRequest|Object)} request
             * The request to be signed, which can be a XMLHttpRequest or a promise-based request Object (e.g. jqXHR).
             * @param {string} method
             * Must be defined in the supported_methods.
             * @param {string} path
             * End point's full URL path, including schema, port, query string, etc. It must already be URL encoded.
             * @param {object} signed_headers
             * Signed headers.
             * @param {string} content_type
             * Content type.
             * @param {string} body
             * Body.
             * @returns {string}
             */
            value: function sign(_ref2) {
                var request = _ref2.request,
                    method = _ref2.method,
                    path = _ref2.path,
                    _ref2$signed_headers = _ref2.signed_headers,
                    signed_headers = _ref2$signed_headers === undefined ? {} : _ref2$signed_headers,
                    _ref2$content_type = _ref2.content_type,
                    content_type = _ref2$content_type === undefined ? this.config.default_content_type : _ref2$content_type,
                    _ref2$body = _ref2.body,
                    body = _ref2$body === undefined ? '' : _ref2$body;
    
                // Validate input. First 3 parameters are mandatory.
                //if (!request || !AcquiaHttpHmac.isXMLHttpRequest(request) && !AcquiaHttpHmac.isPromiseRequest(request)) {
                // throw new Error('The request is required, and must be a XMLHttpRequest or promise-based request Object (e.g. jqXHR).');
                //}
                if (this.SUPPORTED_METHODS.indexOf(method) < 0) {
                    throw new Error('The method must be "' + this.SUPPORTED_METHODS.join('" or "') + '". "' + method + '" is not supported.');
                }
                if (!path) {
                    throw new Error('The end point path must not be empty.');
                }
    
                /**
                 * Convert an object of parameters to a string.
                 *
                 * @param {object} parameters
                 * Header parameters in key: value pair.
                 * @param value_prefix
                 * The parameter value's prefix decoration.
                 * @param value_suffix
                 * The parameter value's suffix decoration.
                 * @param glue
                 * When join(), use this string as the glue.
                 * @param encode
                 * When true, encode the parameter's value; otherwise don't encode.
                 * @returns {string}
                 */
                var parametersToString = function parametersToString(parameters) {
                    var value_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '=';
                    var value_suffix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
                    var glue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '&';
                    var encode = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
    
                    var parameter_keys = Object.keys(parameters),
                        processed_parameter_keys = [],
                        processed_parameters = {},
                        result_string_array = [];
    
                    // Process the headers.
                    // 1) Process the parameter keys into lowercase, and
                    // 2) Process values to URI encoded if applicable.
                    parameter_keys.forEach(function (parameter_key) {
                        if (!parameters.hasOwnProperty(parameter_key)) {
                            return;
                        }
                        var processed_parameter_key = parameter_key.toLowerCase();
                        processed_parameter_keys.push(processed_parameter_key);
                        processed_parameters[processed_parameter_key] = encode ? encodeURIComponent(parameters[parameter_key]) : parameters[parameter_key];
                    });
    
                    // Process into result string.
                    processed_parameter_keys.sort().forEach(function (processed_parameter_key) {
                        if (!processed_parameters.hasOwnProperty(processed_parameter_key)) {
                            return;
                        }
                        result_string_array.push('' + processed_parameter_key + value_prefix + processed_parameters[processed_parameter_key] + value_suffix);
                    });
                    return result_string_array.join(glue);
                };
    
                /**
                 * Generate a UUID nonce.
                 *
                 * @returns {string}
                 */
                var generateNonce = function generateNonce() {
                    var d = Date.now();
                    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                        var r = (d + Math.random() * 16) % 16 | 0;
                        d = Math.floor(d / 16);
                        return (c == 'x' ? r : r & 0x7 | 0x8).toString(16);
                    });
                };
    
                /**
                 * Determine if this request sends body content (or skips silently).
                 *
                 * Note: modern browsers always skip body at send(), when the request method is "GET" or "HEAD".
                 *
                 * @param body
                 * Body content.
                 * @param method
                 * The request's method.
                 * @returns {boolean}
                 */
                var willSendBody = function willSendBody(body, method) {
                    var bodyless_request_types = ['GET', 'HEAD'];
                    return body.length !== 0 && bodyless_request_types.indexOf(method) < 0;
                };
    
                // Compute the authorization headers.
                var nonce = generateNonce(),
                    parser = AcquiaHttpHmac.parseUri(path),
                    authorization_parameters = {
                        id: this.config.public_key,
                        nonce: request.id,
                        realm: this.config.realm,
                        version: this.config.version
                    },
                    x_authorization_timestamp = Math.floor(Date.now() / 1000).toString(),
                    x_authorization_content_sha256 = willSendBody(body, method) ? CryptoJS.SHA256(body).toString(CryptoJS.enc.Base64) : '',
                    signature_base_string_content_suffix = willSendBody(body, method) ? '\n' + 'application/json' + '\n' + x_authorization_content_sha256 : '',
                    site_port = parser.port ? ':' + parser.port : '',
                    site_name_and_port = '' + parser.hostname + site_port,
                    url_query_string = parser.search,
                    signed_headers_string = parametersToString(signed_headers, ':', '', '\n', false),
                    signature_base_signed_headers_string = signed_headers_string === '' ? '' : signed_headers_string + '\n',
                    signature_base_string = method + '\n' + site_name_and_port + '\n' + (parser.pathname || '/') + '\n' + url_query_string + '\n' + parametersToString(authorization_parameters) + '\n' + signature_base_signed_headers_string + x_authorization_timestamp + signature_base_string_content_suffix,
                    authorization_string = parametersToString(authorization_parameters, '="', '"', ','),
                    authorization_signed_headers_string = encodeURI(Object.keys(signed_headers).join('|||||').toLowerCase().split('|||||').sort().join(';'));
                console.log('signature_base_string:' + signature_base_string);
                var signature = encodeURI(CryptoJS.HmacSHA256(signature_base_string, this.config.parsed_secret_key).toString(CryptoJS.enc.Base64));
    
                var authorization = 'acquia-http-hmac ' + authorization_string + ',headers="' + authorization_signed_headers_string + '",signature="' + signature + '"';
                console.log('authorization:' + authorization);
    
                // Set the authorizations headers.
                request.acquiaHttpHmac = {};
                request.acquiaHttpHmac.timestamp = x_authorization_timestamp;
                request.acquiaHttpHmac.nonce = nonce;
    
                console.info('authorization',x_authorization_timestamp,x_authorization_content_sha256,authorization)
    
    
                pm.request.headers.add( {
                    key: 'X-Authorization-Timestamp', value: x_authorization_timestamp
                } );
    
                pm.request.headers.add( {
                    key: 'X-Authorization-Content-SHA256', value: x_authorization_content_sha256
                } );
    
                pm.request.headers.add( {
                    key: 'Authorization', value: authorization
                } );
    
                // pm.environment.set('acqHmacTimestamp', x_authorization_timestamp);
                // pm.environment.set('acqHmacHeader', authorization);
                // pm.environment.set('acqHmacContentSha', x_authorization_content_sha256);
    
                void 0;
                void 0;
                void 0;
                void 0;
                void 0;
            }
        }, {
            key: 'hasValidResponse',
    
    
            /**
             * Check if the request has a valid response.
             *
             * @param {XMLHttpRequest|Object} request
             * The request to be validated.
             * @returns {boolean}
             * TRUE if the request is valid; FALSE otherwise.
             */
            value: function hasValidResponse(request) {
                var signature_base_string = request.acquiaHttpHmac.nonce + '\n' + request.acquiaHttpHmac.timestamp + '\n' + request.responseText,
                    signature = CryptoJS.HmacSHA256(signature_base_string, this.config.secret_key).toString(CryptoJS.enc.Base64),
                    server_signature = request.getResponseHeader('X-Server-Authorization-HMAC-SHA256');
    
                void 0;
                void 0;
                void 0;
    
                return signature === server_signature;
            }
        }], [{
            key: 'isXMLHttpRequest',
            value: function isXMLHttpRequest(request) {
                if (request instanceof XMLHttpRequest || request.onreadystatechange) {
                    return true;
                }
                return false;
            }
    
            /**
             * Check if the request is a promise-based request Object (e.g. jqXHR).
             *
             * @param {(XMLHttpRequest|Object)} request
             * The request to be signed, which can be a XMLHttpRequest or a promise-based request Object (e.g. jqXHR).
             * @returns {boolean}
             * TRUE if the request is a promise-based request Object (e.g. jqXHR); FALSE otherwise.
             */
    
        }, {
            key: 'isPromiseRequest',
            value: function isPromiseRequest(request) {
                return request.hasOwnProperty('setRequestHeader') && request.hasOwnProperty('getResponseHeader') && request.hasOwnProperty('promise');
            }
    
            /**
             * Implementation of Steven Levithan uri parser.
             *
             * @param {String} str The uri to parse
             * @param {Boolean} strictMode strict mode flag
             * @return {Object} parsed representation of a uri
             */
    
        }, {
            key: 'parseUri',
            value: function parseUri(str) {
                var strictMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    
                var o = {
                        key: ["source", "protocol", "host", "userInfo", "user", "password", "hostname", "port", "relative", "pathname", "directory", "file", "search", "hash"],
                        q: {
                            name: "queryKey",
                            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
                        },
                        parser: {
                            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                            loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
                        }
                    },
                    m = o.parser[strictMode ? "strict" : "loose"].exec(str),
                    uri = {},
                    i = 14;
    
                while (i--) {
                    uri[o.key[i]] = m[i] || "";
                }uri[o.q.name] = {};
                uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
                    if ($1) uri[o.q.name][$1] = $2;
                });
    
                return uri;
            }
        }]);
    
        return AcquiaHttpHmac;
    }();
    
    var method = request.method.toUpperCase(),
        path = request.url.replace(/{{(\w+)}}/g, function (m, m1) {
            return pm.environment.get(m1) || m;
        }),
        signed_headers = {},
        content_type = "application/json",
        body = request.data;
    
    var sign_parameters = {
        request, method, path, signed_headers, content_type, body
    };
    
    var hmac_config = {
        realm: hmacRealm,
        public_key: publicKey,
        secret_key: secretKey
    };
    const HMAC = new AcquiaHttpHmac(hmac_config);
    HMAC.sign(sign_parameters);
```

[Previous page](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708.md?page=1)

[Next page](https://community.postman.com/t/setting-headers-for-entire-collection-folder/708.md?page=3)
