# Postman Authentication in Pre- run script Fails - Automatic token generation in single request

**URL:** <https://community.postman.com/t/postman-authentication-in-pre-run-script-fails-automatic-token-generation-in-single-request/15608>\
**Category:** Help Hub\
**Tags:** collections, authentication\
**Created:** [September 4, 2020, 8:41am UTC](https://community.postman.com/t/postman-authentication-in-pre-run-script-fails-automatic-token-generation-in-single-request/15608 "2020-09-04T08:41:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![SwathySubramani](https://avatars.discourse-cdn.com/v4/letter/s/ecb155/32.png) [@SwathySubramani](https://community.postman.com/u/SwathySubramani)\
**Post date:** [September 4, 2020, 8:41am UTC](https://community.postman.com/t/postman-authentication-in-pre-run-script-fails-automatic-token-generation-in-single-request/15608/1 "2020-09-04T08:41:33Z")

</div>

I am trying to create a pre-run script which gets the bearer token and sets it to the environment variable. The variable is used for authentication for PostDetails request.

```auto
Facing the Error : jsonerror :Unexpected token '<' at 3:1 <!-- Copyright (C) Microsoft Corporation. All rights reserved. --> ^

```

Below is the script:

```auto
// get the collection 
var sdk = require('postman-collection');

// construct the bearer token request
var tokenRequest = new sdk.Request({
    url: 'https://login.microsoftonline.com/tenantname.com/oauth2/token', 
    method: 'GET',
    header: [
        new sdk.Header({
            key: 'content-type',
            value: 'application/x-www-form-urlencoded'
        }),
        new sdk.Header({
            key: 'Connection',
            value: 'keep-alive'
        }),
    ],
    body: {
        mode: 'application/x-www-form-urlencoded',
        raw: JSON.stringify({
            client_id: 'cccccccccccccccccccccccccccccc',
            client_secret: 'ssssssssssssssssssssssssss',
            grant_type: 'Client_credentials',
            resource: 'https://usnconeboxax1aos.cloud.onebox.dynamics.com'
        })
    }

  });

// send bearer token request
 pm.sendRequest(tokenRequest, function (err, response) {
      if (err) {
          throw err;
      }
      
      if (response.code !== 200) {
          throw new Error('Could not log in.');
      }
      pm.environment.set("token", response.json().access_token);
      console.log('New token has been set: ${response.json().access_token}');
  });

```

Kindly let me know whats wrong or missing and how it can be troubleshooted.

---

<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:** [September 4, 2020, 8:53am UTC](https://community.postman.com/t/postman-authentication-in-pre-run-script-fails-automatic-token-generation-in-single-request/15608/2 "2020-09-04T08:53:19Z")

</div>

Hey @SwathySubramani

Welcome to the community! 🏆

I _think_ something like this added to the `pre-request script` might help:

```auto
var tokenRequest = {
    url: 'https://login.microsoftonline.com/tenantname.com/oauth2/token', 
    header: {
            'Content-Type':'application/x-www-form-urlencoded',
            'Connection':'keep-alive'
    },
    body: {
        mode: 'application/x-www-form-urlencoded',
        urlencoded : [
            { key: 'client_id', value: 'cccccccccccccccccccccccccccccc'},
            { key: 'client_secret', value: 'ssssssssssssssssssssssssss'},
            { key: 'grant_type', value: 'Client_credentials'},
            { key: 'resource', value: 'https://usnconeboxax1aos.cloud.onebox.dynamics.com'}
        ]
    }
  };

// send bearer token request
pm.sendRequest(tokenRequest, function (err, response) {
    if (err) {
        throw err;
    }
      
    if (response.code !== 200) {
        throw new Error('Could not log in.');
    }
    pm.environment.set("token", response.json().access_token);
    console.log(`New token has been set: ${response.json().access_token}`);
});

```

This is a handy resource when using `pm.sendRequest()`:

> <https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990>

---

<div class="post-metadata">

**Author:** ![SwathySubramani](https://avatars.discourse-cdn.com/v4/letter/s/ecb155/32.png) [@SwathySubramani](https://community.postman.com/u/SwathySubramani)\
**Post date:** [September 4, 2020, 9:15am UTC](https://community.postman.com/t/postman-authentication-in-pre-run-script-fails-automatic-token-generation-in-single-request/15608/3 "2020-09-04T09:15:08Z")

</div>

@dannydainton: Thanks for the quick resolution. The shared script worked.
