postmanpostman-pre-request-script

Postman access vault value in a pre-request script


I'm using Postman v11.14.1

I want to build a postman workspace shared by our team containing requests to some APIs.

I've put all credentials into Postman vault to avoid storing them in a Postman cloud. For example DEV_SYS1_CLIENT_ID, STAGE_SYS1_CLIENT_ID, etc.

Then I've defined our environments: Dev, Stage, etc. Then I define environment variables. For example in Dev: SYS1_CLIENT_ID={{vault:DEV_SYS1_CLIENT_ID}}. For Stage: SYS1_CLIENT_ID={{vault:STAGE_SYS1_CLIENT_ID}}.

Then I have a SOAP API call. Authentication data is part of SOAP request body.

    <soap:Header>
        <auth>
         <clientId>{{SYS1_CLIENT_ID}}</clientId>
         <signature algorithm="HMAC-SHA256">{{signature}}</signature>
       </auth>
       ...

To calculate the signature value I've created a pre-request script for the Postman collection. It is supposed to use Environment variables to build the signature value. I use the following method to get Environment variable value:

pm.environment.get("SYS1_CLIENT_ID")

The problem is that the code results in {{vault:DEV_SYS1_CLIENT_ID}} instead of actual value from vault. Can I get actual value there instead of the reference?

Is there another way to inject values built from Vault data into request body? I know that I can set all credentials directly into Environment variables. But I don't think it's a correct way to manage such a data.


Solution

  • I've came up with the following solution.

    #1 - enable access to use vault variables in the script sandbox as Danny Dainton suggested above

    #2 - write a little helper function to resolve actual secret value instead of {{vault:DEV_SYS1_CLIENT_ID}}:

        const getSecretValue = async (variableName) => {
          const value = pm.environment.get(variableName);       
          if (value && value.startsWith('{{vault:')) {
            const vaultKey = value.substring(8, value.length - 2);
            const vaultValue = await pm.vault.get(vaultKey);
            return vaultValue;
          }
          return value;
        };
    

    #3 Use the function to get actual secret value:

        const clientId = await getSecretValue("SYS1_CLIENT_ID"); 
        // here clientId contains actual secret value, not {{vault:DEV_SYS1_CLIENT_ID}}