Issue: Authorization Works in Postman App, but 401 in Postman CLI

I’m experiencing an issue where a collection works as expected in the Postman App (including setting the bearerToken for authentication), but when I run the same collection in Postman CLI (Newman), I receive a 401 Unauthorized error for all requests.

Details:

  • Pre-request Script: The bearerToken is retrieved through a POST request in the Pre-request Script and set as an environment variable. The token is used dynamically in the Authorization header.

  • Headers: The Authorization header is set as Bearer {{bearerToken}}, and Content-Type is set to application/json. These headers are correctly printed in both the App and CLI.

  • Environment: The correct environment file is used in both Postman App and CLI.

  • CLI Command: I’m running the collection using:

    postman run <collection-file> --environment <environment-file> --verbose
    
  • Pre-request Script (Key Sections):

    // Fetching bearer token
    pm.sendRequest({
      url: pm.environment.get("AuthURL"),
      method: 'POST',
      body: {
        mode: 'urlencoded',
        urlencoded: [
          { key: 'client_id', value: pm.environment.get("ClientID") },
          { key: 'scope', value: pm.environment.get("Scope") },
          { key: 'client_secret', value: pm.environment.get("Secret") },
          { key: 'grant_type', value: 'client_credentials' }
        ]
      }
    }, (err, res) => {
      if (!err) {
        pm.environment.set("bearerToken", res.json().access_token);
      }
    });
    
    // Setting headers
    pm.request.headers.add({ key: 'Content-Type', value: 'application/json' });
    pm.request.headers.add({ key: 'Authorization', value: `Bearer ${pm.environment.get("bearerToken")}` });
    

Behavior:

  • In Postman App: The collection runs correctly, and responses are valid.
  • In Postman CLI: The collection fails with a 401 Unauthorized error for all requests, despite the token being set and headers printed correctly.

Questions:

  1. Why does the collection work in the Postman App but return a 401 Unauthorized error in Postman CLI?
  2. Could there be a difference in how the token or headers are handled between Postman App and CLI?
  3. Any ideas for a proposed solution or what I could try?

Thanks for your help!

Just one obvious point, but sometimes the obvious is the “gotcha” - you are using the same Environment for both the interactive and CLI test runs?

Second point, doesn’t directly diagnose the issue, but if this eliminates the problem we’ll all be happy, right? What you are doing in your Pre-Request script, I typically execute as a separate Postman request and then, in the Post-Request script of that Authentication request, I poke the token into an Environment variable which is then referenced on the Authentication tab of the collection so that all subsequent requests which are inheriting Authentication from the collection are passing the correct authentication token on all successive requests.

Hopefully, there’s something here which can help resolve your issue. If you hit upon a different solution, please post here. I’m interested to see the solution. I too have faced those issues where it works perfectly in my interactive Postman, but then when executing via CLI in my pipeline it behaves slightly differently. Good luck!

1 Like

Yes I’m working with the same Collection and Environment in both Postman app and CLI.

Right, as far as the separate Post request. I can try and see if that resolves it but the rest of the steps I’m doing the exact same way. I have a token as an environment variable which I set in the Pre-request script. That token is referenced in my Authentication tab for the whole collection. Each folder inherits from it.

I’ve also printed out my token environment variable in my individual request Pre-request scripts to verify it was set correctly in my environment, and I got what I was expecting, so it seems that the token is set correctly.

Update: Tried doing a separate Post request before the other requests that will set the token. It still works in Postman directly but not in CLI

@danny-dainton I noticed you’re active in the postman forum and are a marked as a leader. Wondering if you have any thoughts on this issue?

Shouldn’t that be -

postman collection run {collection-file} --environment {environment-file} --verbose

I’ve actually updated that and have copied it directly from the Postman command given for automating runs with Postman CLI. So this is what it looks like now

postman collection run {{collectionId}} -e {{environmentId}}

I used verbose to figure out what’s going on but that’s what it looks like now

U can use --insecure in newman in the end of command
Newman run collection.json -e environment.json --insecure

But also if u are using multiple collections and in postman when u run authorization request in different collection and mainc request in different then it shouldnot work u need to add authorization request in top of each collection

Hi @timotejiliev. Welcome to the Postman Community :postman:

Are you experiencing this with Postman CLI or with Newman? Both are different tools and I have noticed you use the names interchangeably.

A few recommendations:

  • Ensure that the environment JSON file you’re using contains the same credentials as the
  • The environment file you’re using, ensure to check that you’re using the correct filepath as this is a very common cause for failures. Preferably, store the file in the same folder or path where the command line is being executed from.
  • If you’re using Postman CLI, you can use the UUID(for both collections and environment) on the Postman app directly on the CLI. postman collection run collection-uuid --environment environment-uuid. This will also enable you see your run results on your Postman dashboard and will help you avoid issues with file path or using a wrong environment file.

Hopefully, one of the above helps you resolve the issue.

Just tried it, but I wasn’t able to get it to work

1 Like

I started off using Postman CLI and then upon the recommendation of others I used newman. I ran it without the json but directly through the URL.

I just ran it again with Postman CLI (not newman) and each API call except the first one (Make a call to get the bearer token) failed.

When I run it through Postman directly it works. Just press Run again on the same call and everything is passing.

@gbadebo-bello @yossigeretz @navigation-observe10

The issue was caused because of the initial values for the environment were not up to date. The current values were correct, so I’m assuming that Postman (app, web) used those but when I ran it through CLI it uses the Initial values leading to authentication errors.

I updated the initial values to match the current ones and the authentication problem went away.

1 Like

I see. Glad you’ve been able to resolve it @timotejiliev.

A few notes on current and initial values in Postman.

  • Initial values are synced with Postman Cloud and visible to your team or anyone with view access to that collection. Hence, the collection runner can access them even on the CLI.
  • Current values are not synced with Postman Cloud and are only local to you. Hence, they are not shared with your team or anyone with view access to that collection.

This one minute video also explains it very clearly. https://www.youtube.com/watch?v=I6vClap0ajU

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.