# Need a code template for postman pre-request workflow that get oauth2.0 token then use this token to get credential

**URL:** <https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685>\
**Category:** Help Hub\
**Created:** [August 17, 2023, 1:50pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685 "2023-08-17T13:50:53Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![security-geoscienti1](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/security-geoscienti1/32/16583_2.png) [@security-geoscienti1](https://community.postman.com/u/security-geoscienti1)\
**Post date:** [August 17, 2023, 1:50pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/1 "2023-08-17T13:50:53Z")

</div>

## What I needed

1. get new oauth2.0 token from cognito endpoint._(I have clientId, secret, cognito domain, auto\_by\_code, redirect\_url)_ → `token`
2. use this token with something like:  
post below as payload to `https://cognito-identity.ap-southeast-2.amazonaws.com/` and get respnse → res: `IdentityId`,

```auto
{"IdentityPoolId":"ap-southeast-2:${MyPoolID}","Logins":{"cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_MYID":token}}

```

1. use response to post to `https://cognito-identity.ap-southeast-2.amazonaws.com/` → `session credential`

```auto
{"IdentityId":"ap-southeast-2:${IdentityId}","Logins":{"cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_MYID":token}}

```

1. 3 will get a AWS session credential , and set returned credential from 3 to environment.

## Expected

Everytime I run request to test API covered by AWS sign4.0, I can get new credential that be set to AWS signature of postman authorization.

## Current

My first step always get 405:“Method not allowed” error..

```js
const postRequest = {
    url: 'https://xxxxxxx.auth.ap-southeast-2.amazoncognito.com/oauth2/token',
    method: 'POST',
    auth: {
        user: 'xxxxxxxxxxxxxxxxxx',
        password: 'xxxxxxxxxxxxxxx'
    },
    headers:{
        "Content-Type":"application/x-www-form-urlencoded"
    },
    form: {
        grant_type: 'authorization_code'
    }
}

pm.sendRequest(postRequest, (error, response) => {
    console.log(response)
});

```

---

<div class="post-metadata">

**Author:** ![security-geoscienti1](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/security-geoscienti1/32/16583_2.png) [@security-geoscienti1](https://community.postman.com/u/security-geoscienti1)\
**Post date:** [August 17, 2023, 1:51pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/2 "2023-08-17T13:51:47Z")

</div>

Or is there a way to chain multiple auth together?

1. oauth2.0
2. post1 → post2 → credential
3. aws signiture

---

<div class="post-metadata">

**Author:** ![kevinc-postman](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/kevinc-postman/32/12774_2.png) [@kevinc-postman](https://community.postman.com/u/kevinc-postman)\
**Post date:** [August 17, 2023, 9:56pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/3 "2023-08-17T21:56:30Z")

</div>

Hey @security-geoscienti1 !

So it seems like you’re trying to automate the process of obtaining your AWS creds via Cognito in Postman’s pre-request script, which is a great way to ensure you’re always testing with valid credentials. Let’s break this down step-by-step.

### 1. Getting the OAuth2.0 Token

The error you’re seeing, `405: "Method not allowed"`, often indicates that the HTTP method (in this case, POST) isn’t supported for the given endpoint. However, the code you provided for this step looks generally correct for obtaining an OAuth2.0 token.

The `grant_type` you’re using is `authorization_code`, which typically requires a few more parameters like `code`, `redirect_uri`, etc. Ensure that you’re providing all required parameters.

Also, consider checking if the endpoint you’re hitting supports the POST method for token generation.

### 2. Obtaining IdentityId

Once you’ve obtained the token, you can use it to get the `IdentityId`:

```js
const token = response.json().access_token;

const identityRequest = {
    url: 'https://cognito-identity.ap-southeast-2.amazonaws.com/',
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            "IdentityPoolId": "ap-southeast-2:${MyPoolID}",
            "Logins": {
                "cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_MYID": token
            }
        })
    }
};

pm.sendRequest(identityRequest, (error, res) => {
    const identityId = res.json().IdentityId;
    // Continue to the next step with identityId
});

```

### 3. Obtaining AWS Session Credentials

Once you have the `IdentityId`, you can obtain the AWS session credentials:

```js
const credentialRequest = {
    url: 'https://cognito-identity.ap-southeast-2.amazonaws.com/',
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            "IdentityId": `ap-southeast-2:${identityId}`,
            "Logins": {
                "cognito-idp.ap-southeast-2.amazonaws.com/ap-southeast-2_MYID": token
            }
        })
    }
};

pm.sendRequest(credentialRequest, (error, res) => {
    const credentials = res.json();
    // Store credentials in Postman's environment variables
    pm.environment.set('awsAccessKey', credentials.AccessKeyId);
    pm.environment.set('awsSecretKey', credentials.SecretKey);
    pm.environment.set('awsSessionToken', credentials.SessionToken);
});

```

### Summary:

- Ensure the endpoint and method for obtaining the OAuth2.0 token are correct.
- When using `authorization_code` grant type, ensure you provide all required parameters.
- Break the workflow into clear steps and handle each step’s response before moving to the next.

If you continue to face issues, it might be beneficial to check AWS Cognito’s documentation or reach out to AWS support to ensure you’re using the correct endpoints and methods.

Hope this helps! 🙂

---

<div class="post-metadata">

**Author:** ![security-geoscienti1](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/security-geoscienti1/32/16583_2.png) [@security-geoscienti1](https://community.postman.com/u/security-geoscienti1)\
**Post date:** [August 18, 2023, 12:00am UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/4 "2023-08-18T00:00:42Z")

</div>

> [@kevinc-postman](#):
>
> Getting the OAuth2.0 Token

I can skip first step by using npm package `amazon-cognito-identity-js` to get token, but I tried to include the library, seems not work.

two method tried, sendquest to cdn, set variable not work

---

<div class="post-metadata">

**Author:** ![kevinc-postman](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/kevinc-postman/32/12774_2.png) [@kevinc-postman](https://community.postman.com/u/kevinc-postman)\
**Post date:** [August 21, 2023, 9:17pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/5 "2023-08-21T21:17:04Z")

</div>

Postman’s scripting environment does not support importing JavaScript libraries.

For the workflows you’re describing, I’d recommend the following:

1. **Local Script Execution** : Use a local Node.js script to interact with the `amazon-cognito-identity-js` package, then either:

- Store the token in a local environment variable or file.
- Pass the token to Postman directly.

1. **Using Postman Environment Variables** : After obtaining the token from your local script, you can programmatically set a Postman environment variable using Postman’s API. This means your collection runs can fetch the token from the environment when needed.
2. **Newman Integration** : Consider using Newman (Postman’s CLI) for executing your collection runs. With Newman, you have more flexibility to integrate Postman collections into scripts and automation pipelines, and you can leverage the full power of Node.js libraries.

I understand these methods might be a bit more complex than having everything directly in Postman, but they offer greater flexibility and allow for a richer integration with external tools and libraries.

Hope this clarifies things a bit! Let me know if you have any other questions.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/getpostman/user_avatar/community.postman.com/system/32/29796_2.png) [@system](https://community.postman.com/u/system)\
**Post date:** [August 28, 2023, 9:17pm UTC](https://community.postman.com/t/need-a-code-template-for-postman-pre-request-workflow-that-get-oauth2-0-token-then-use-this-token-to-get-credential/50685/6 "2023-08-28T21:17:06Z")

</div>

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