postmanpostman-collection-runnerpostman-pre-request-scriptpostman-testcasepostman-newman

How to set an accessToken in postman by passing the credentials in newman


I have a pre-request Script in my postmancollections.json file which does the following:

const executedOnce = pm.environment.get('executedOnce');
if(executedOnce == 0)
{
    console.log("Getting Access Token");
    const tokenUrl = pm.environment.get('tokenUrl');
    const webApiClientId = pm.environment.get('webApiClientId');
    const scope = pm.environment.get('scope');
    const username = pm.environment.get('username'); 
    const password = pm.environment.get('password');  

    const getTokenRequest = {
        method: 'POST',
        url: tokenUrl,
        body: {
            mode: 'formdata',
            formdata:[
                {key: 'client_id', value: webApiClientId},
                {key: 'scope', value: scope},
                {key: 'grant_type', value: 'password'}, 
                {key: 'username', value: username},
                {key: 'password', value: password}
            ]
        }
    };

    pm.sendRequest(getTokenRequest, (err, response) => {
        const jsonResponse = response.json();
        const newAccessToken = jsonResponse.access_token;
        pm.environment.set('accessToken', newAccessToken);
        pm.environment.set('executedOnce', 1)
        console.log("Access Token Obtained");
    });

From my newman, I pass the username and password which are my environment variables. The access Token is getting generated, but is not getting set to the environment variable, because of which my test scripts in collection is failing.

How to update the environment variable accessToken which is dynamically generated after passing username and password in newman?

Some answers suggest an export command at the end of newman run like below:

newman run testscripts_postman.json -e localenvironment.json --env-var "username=ABC" --env-var "password=abc" --export-environment localenvironment.json

But how will this run in Azure DevOps pipeline if I add an export?


Solution

  • Using pm.variables() all other varaibles and pm.environment() for password and username.

    it use to define a local variable within a collection. Newman can using it without environmental variables handling.

    enter image description here

    enter image description here

    Demo I will use Keycloak v19(docker image is quay.io/keycloak/keycloak:legacy) for getting an access token Then call to get user list with that token.

    In Pre-request Script tab

    const executedOnce = pm.variables.get('executedOnce');
    console.log('executedOnce: ' + executedOnce);
    if(executedOnce == 0)
    {
        console.log("Getting Access Token");
        const tokenUrl = pm.variables.get('tokenUrl');
        const webApiClientId = pm.variables.get('webApiClientId');
        const scope = pm.variables.get('scope');
        const username = pm.environment.get('username'); 
        const password = pm.environment.get('password'); 
        console.log("tokenUrl: " + tokenUrl);
    
        const getTokenRequest = {
            method: 'POST',
            url: tokenUrl,
            body: {
                mode: 'urlencoded',
                urlencoded:[
                    {key: 'client_id', value: webApiClientId},
                    {key: 'scope', value: scope},
                    {key: 'grant_type', value: 'password'}, 
                    {key: 'username', value: username},
                    {key: 'password', value: password}
                ]
            }
        };
    
        pm.sendRequest(getTokenRequest, (err, response) => {
            const jsonResponse = response.json();
            const newAccessToken = jsonResponse.access_token;
            pm.variables.set('accessToken', newAccessToken);
            pm.variables.set('executedOnce', 1)
            console.log("Access Token Obtained");
        });
    }
    

    enter image description here

    Note, Keycloak needs mode: 'urlencoded' If your POST body mode is formdata, to use it.

    In Authorization tab enter image description here

    In Test tab

    var jsonData = JSON.parse(responseBody);
    console.log("first user", jsonData[0]);
    

    enter image description here

    Test run in Postman enter image description here

    Export collection (JSON) and environment variables(JSON)

    enter image description here

    enter image description here

    Run by newman from terminal

     newman run 1-demo.postman_collection.json  -e demo.postman_environment.json
    

    enter image description here *Note, normally get token by Tests tab instead Pre-request Script tab in here

    It is more easy due to just get token by separate API then all other API using it.