How to Create Postman Collection and use Pre-request Script for Authorization

Summary

  • Postman collections are powerful tools that allow you to store and organize API requests, variables, and scripts.
  • They help streamline API testing and development by making requests more dynamic and efficient.

What is Postman Collection?

  1. Postman collections can be created manually by adding individual requests or generated automatically from API documentation.
  2. They are sets of API requests that can be organized and shared, and they support variables and scripts for added flexibility and automation.

Why to use Postman Collection?

  1. aiTest assists in identifying security vulnerabilities and weaknesses in your application’s URLs and APIs.
  2. By performing security testing, you can identify potential security risks, such as unauthorized access, data leaks, or injection attacks.

Benefits

  1. Efficiency: Postman collections automate the testing process, allowing for frequent and consistent execution of tests.
  2. Early Issue Identification: By testing URLs and APIs early in the development cycle, issues can be identified and resolved promptly.
  3. Security Testing: aiTest helps identify security vulnerabilities and risks in the application, leading to improved security measures.

How to Create a Collection in Postman?

  1. Sign up using your E-mail or Google account.
  2. Once you have reached the Postman dashboard, navigate to the left-side menu and select the Workspaces. Create Workspaces
  3. Click on the Workspaces option. Configure Workspaces
  4. Configure new Workspace in postman, Once you created workspace it will get selected by default or you can change it from list. Now we have to create new collection in our newly created workspace.
  5. On left side of dashboard there is a Collection option, click on it you will see ‘ + ‘ icon. New Collection Click on “ + “ icon, it will create collection with name “New collection”, you can update it as per your collection name.
  6. Once you are ready with your new collection, Select it from Collection list. Now we start adding request in our collection,
    • a)In selected collection you will see “ … “(three dots).
    • b)click on those, you will see Add request option in list. Add Request
  7. Select Add request, it will open new drawer to configure request. Request Details
  8. Add basic request details such as “Request type(can be selected from list get, post, put, delete etc …)” & “URL”.
  9. Additionally you need to update “Body”, “Authorization”, “Headers” & “Pre-request Script” as per your request requirements, Give name to your request , its optional.
  10. Save your request and click send button. It will run given request and will show response on same postman screen. Run Collection
  11. Inside the Collection there is “Variables” option and can be use to set Collection Variables.
  12. To Run collection manually in postman Run collection Option is provided. To run it, again in selected collection click on it ‘…’, you will get Run collection option in list. Select it and configure Run configuration details and Run Collection.

Collection Variables

Before running the Script in collection, Set following Collection Variables

  • cognitoClientId :< client id >;
  • authorizationCode :**-4978-99b7-**;
  • congnitoRedirectUri :http://localhost:8080/;
  • cognitoTokenUrl :https://login-marxeed-dev.auth.us-east-1.amazoncognito.com/oauth2/token;
  • cognitoClientSecret :None;
  • cognitoRefreshToken :None;
  • cognitoIdToken :None;
  • cognitoAccessTokenExpiry :None;
  • cognitoAccessToken :None;

How to take Authorization Code from AWS Cognito?

  1. Sign up using your official E-mail.
  2. Once you have reached the AWS dashboard.
  3. Search Cognito option in the serach bar and click on Cognito option.
  4. Click on your user pool.
  5. Click on App Integration option.
  6. In App clients and analytics we have to click on app client name.
  7. In Hosted UI click on View Hosted UI option.
  8. Then Sign in with your email and password.
  9. Copy that Authorization Code from address bar.

Note:

  1. Please Update cognitoClientId, authorizationCode, cognitoTokenUrl & congnitoRedirectUri with your values.
  2. Make sure you are using cognitoIdToken variable as value for Bearer Token in Authorization section of each request in collection.
  3. To Run Pre-request Script in Collection need to update Authorization Code in Collection variable named as authorizationCode.

Pre-request Script for Authorization

  • To call authenticated request , Pre-request Script can be used.
  • Pre-request Script is javascript which can be added in Pre-request Script section of collection.

Pre-request Script

  
var cognitoClientId = pm.collectionVariables.get("cognitoClientId");
var authorizationCode = pm.collectionVariables.get("authorizationCode");
var congnitoRedirectUri = pm.collectionVariables.get("congnitoRedirectUri");
var cognitoRefreshToken = pm.collectionVariables.get("cognitoRefreshToken");
var cognitoIdToken = pm.collectionVariables.get("cognitoIdToken");
var cognitoTokenUrl =  pm.collectionVariables.get("cognitoTokenUrl");
console.log(authorizationCode)
console.log(cognitoTokenUrl)

const postRequestwithCode = {
   url: cognitoTokenUrl,
   method: 'POST',
   timeout: 0,
   header: {
      "Content-Type": "application/x-www-form-urlencoded"
   },
   body: {
      mode: 'urlencoded',
      urlencoded: [{
            key: "grant_type",
            value: "authorization_code"
         },
         {
            key: "redirect_uri",
            value: congnitoRedirectUri
         },
         {
            key: "client_id",
            value: cognitoClientId
         },
         {
            key: "code",
            value: authorizationCode
         },
      ]
   }
};

const postRequestwithRefreshToken = {
   url: cognitoTokenUrl,
   method: 'POST',
   timeout: 0,
   header: {
      "Content-Type": "application/x-www-form-urlencoded"
   },
   body: {
      mode: 'urlencoded',
      urlencoded: [{
            key: "grant_type",
            value: "refresh_token"
         },
         {
            key: "redirect_uri",
            value: congnitoRedirectUri
         },
         {
            key: "client_id",
            value: cognitoClientId
         },
         {
            key: "refresh_token",
            value: cognitoRefreshToken
         },
      ]
   }
};

console.log(cognitoIdToken)
if (!cognitoIdToken || cognitoIdToken == "null") {
   console.log('Tokens are missing from env getting token with code')
   pm.sendRequest(postRequestwithCode, function (err, res) {
      console.log(err ? err : res.json());
      var responseJson = res.json();
      console.log(typeof responseJson);
      if ( 'error'  in responseJson) {
         console.log('Error while getting access token by using authorization code', responseJson);
      }
      else
      {
         console.log(responseJson);
         pm.collectionVariables.set('cognitoIdToken', responseJson['id_token']);
         pm.collectionVariables.set('cognitoAccessToken', responseJson['access_token']);
         pm.collectionVariables.set('cognitoRefreshToken', responseJson['refresh_token']);
         var expiryDate = new Date();
         expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
         pm.collectionVariables.set('cognitoAccessTokenExpiry', expiryDate.getTime());

      }

   });
} else if (pm.collectionVariables.get('cognitoAccessTokenExpiry') <= (new Date()).getTime()) {
   console.log('Token Expired , getting new id token with refresh token')
   pm.sendRequest(postRequestwithRefreshToken, function (err, res) {
      console.log(err ? err : res.json());
     var responseJson = res.json();
     if ( 'error'  in responseJson) {
         console.log('Error while getting access token by using existing access token', responseJson);
      }
      else
      {
         console.log(responseJson);
         pm.collectionVariables.set('cognitoIdToken', responseJson['id_token']);
         pm.collectionVariables.set('cognitoAccessToken', responseJson['access_token']);
         pm.collectionVariables.set('cognitoRefreshToken', responseJson['refresh_token']);
         var expiryDate = new Date();
         expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
         pm.collectionVariables.set('cognitoAccessTokenExpiry', expiryDate.getTime());

      }

   })
} else {
   console.log('Token is valid, using it ')
}
  

Questions Answered

  • How to Create Collection in Postman?
  • What is Pre-Request Script?
×

Subscribe

The latest tutorials sent straight to your inbox.