Scheduled runs throws 401Unauthorized but manual run passes

I have scheduled a collection run which is throwing 401 Unauthorized error for all the requests in the collection. But it is passing when ran manually.

I have refreshed the Oauth2.0 token that I am using and included pre-request script for token authorization. But it didn’t resolve the issue.

I am trying to understand is there any pre-requisite for schedule runs in POSTMAN and how to resolve this issue. Any help would be much appreciated.

Thanks in advance.!

I don’t really use scheduled runs (apart from the one time in the 15 days of Postman for Testers).

Does the schedule run record the request\response somewhere in the app?

Hopefully you should be able to see the request that gets sent (similar to what you get in the console logs).

Have a look at the details and see if any of the variables you need for authentication are missing or incorrect.

Are you using an environment to store those confidential elements and is the environment selected for the scheduled run?

Can you share your script that you are generating the token with?

I am storing the confidential data in environmental variables and the same environment is selected while scheduled run configuration.

Logs are showing only 401 Unauthorized.

I am creating access token at collection level as shown below

I have tried including token generation process in pre-request script. Below is the code that I have used as a trial for resolution.

//OAuth2.0 Authentication
const oauthConfig = {

authorizationURL: '{{authurl}}',
redirectURI: '{{callback}}',
clientID: '{{clientid}}',
responseType: 'token'

};

// Function to initiate the OAuth 2.0 flow
function initiateOAuthFlow() {
const authURL = ${oauthConfig.authorizationURL}?client_id=${oauthConfig.clientID}&redirect_uri=${oauthConfig.redirectURI}&response_type=${oauthConfig.responseType};

// Log the authorization URL and instruct the user to visit it in their browser
console.log('Please visit the following URL to complete the OAuth 2.0 flow:');
console.log(authURL);

}

I can’t see how that code will trigger anything.

You’ve defined an object and a function, but I can’t see where you trigger the function.

The function also doesn’t seem to actually do anything apart from define two variables.

You can’t read environment variables in scripts using that method. You can only use the curly brackets method {{}} in certain places, like the authorisation helpers, the URL and body.

Using variables in scripts | Postman Learning Center

The authorization screenshot using the helper also looks incomplete.

Where is the token name for the “Configure New Token”?

If this requires user interaction with the browser to generate the token, then this isn’t going to work as a Scheduled run.

What I don’t know is how the Scheduled runs consume the environment files. Whether they are able to read the current values or not. If you run this against the CLI (or Newman), then the current values are not exported, I don’t know if its the same for scheduled runs.

The following is an example of an OAuth 2.0 authentication to Microsoft so you can see how the pre-request script method would work. You need to change it to match the OAuth grant type you are using.

let currentDateTime = Date.now();
let tokenExpiry = pm.environment.get("bearerTokenExpiresOn")
// console.log("currentDateTime: " + currentDateTime);
// console.log("tokenExpiry: " + tokenExpiry);
if (!pm.environment.get("bearerToken") || currentDateTime > tokenExpiry) {
    pm.test("Pre-request check for Environment Variables", function () {
        let vars = ['clientId', 'clientSecret', 'tenantId', 'username', 'password', 'scope'];
        vars.forEach(function (item) {
            // console.log(item);
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.undefined;
            pm.expect(pm.environment.get(item), item + " variable not set").to.not.be.empty;
        });
        pm.sendRequest({
            url: 'https://login.microsoftonline.com/' + pm.environment.get("tenantId") + '/oauth2/v2.0/token',
            method: 'POST',
            header: 'Content-Type: application/x-www-form-urlencoded',
            body: {
                mode: 'urlencoded',
                urlencoded: [
                    { key: "client_id", value: pm.environment.get("clientId"), disabled: false },
                    { key: "scope", value: pm.environment.get("scope"), disabled: false },
                    { key: "username", value: pm.environment.get("username"), disabled: false },
                    { key: "password", value: pm.environment.get("password"), disabled: false },
                    { key: "client_secret", value: pm.environment.get("clientSecret"), disabled: false },
                    { key: "grant_type", value: "password", disabled: false },
                ]
            }
        }, function (err, res) {
            if (err) {
                console.log(err);
            } else {
                pm.test("Pre-request Microsoft login Status code is 200", () => {
                    pm.expect(res).to.have.status(200);
                    let resJson = res.json();
                    // console.log(resJson);
                    pm.environment.set("bearerToken", resJson.id_token);
                    pm.environment.set("bearerTokenExpiresOn", Date.now() + resJson.expires_in * 1000);
                    // console.log("bearerTokenExpiresOn: " + pm.environment.get("bearerTokenExpiresOn"));
                });
            }
        });
    });
};

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