Bird
Raised Fist0
Postmantesting~8 mins

Token management in variables in Postman - Framework Patterns

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Framework Mode - Token management in variables
Folder Structure
Postman Collection
├── Environments
│   ├── dev.postman_environment.json
│   ├── staging.postman_environment.json
│   └── prod.postman_environment.json
├── Collections
│   └── API_Tests.postman_collection.json
├── Scripts
│   ├── pre-request-scripts
│   │   └── token-refresh.js
│   └── test-scripts
│       └── common-tests.js
└── README.md
  
Test Framework Layers
  • Environment Variables: Store tokens and environment-specific data (e.g., base URLs, credentials).
  • Pre-request Scripts: Scripts that run before each request to check and refresh tokens if expired.
  • Collections: Group of API requests that use tokens stored in variables for authentication.
  • Test Scripts: Validate responses and token presence after requests.
  • Utilities: Helper scripts for token parsing, expiration checks, and setting variables.
Configuration Patterns
  • Environment Files: Separate environment JSON files for dev, staging, and prod with variables like access_token, refresh_token, and token_expiry.
  • Token Storage: Store tokens in environment variables using pm.environment.set() and retrieve with pm.environment.get().
  • Token Refresh Logic: In pre-request scripts, check if token is expired by comparing current time with token_expiry. If expired, call refresh token API and update variables.
  • Secure Credentials: Store sensitive data like client secrets in environment variables, not in collection scripts.
Test Reporting and CI/CD Integration
  • Newman CLI: Run Postman collections in CI pipelines using Newman to execute tests and generate reports.
  • Report Formats: Generate HTML, JSON, or JUnit reports for test results including token refresh success/failure.
  • CI/CD Pipelines: Integrate Newman runs in pipelines (e.g., GitHub Actions, Jenkins) to validate token management automatically on code changes.
  • Logging: Use console logs in pre-request and test scripts to trace token values and refresh steps during runs.
Best Practices
  1. Use Environment Variables: Always store tokens in environment variables, never hardcode in requests or scripts.
  2. Automate Token Refresh: Implement pre-request scripts to check token expiry and refresh automatically before requests.
  3. Secure Sensitive Data: Keep client secrets and refresh tokens in environment files with restricted access.
  4. Centralize Token Logic: Write reusable helper functions for token parsing and refreshing to avoid duplication.
  5. Validate Tokens: Add test scripts to verify tokens are present and valid after refresh calls.
Self Check

Where in this framework structure would you add a new script to handle token refresh logic?

Key Result
Use environment variables and pre-request scripts to manage and refresh tokens automatically in Postman collections.

Practice

(1/5)
1. In Postman, why is it useful to store an authentication token in an environment variable?
easy
A. To make the token visible to all users of the Postman app
B. To encrypt the token for security
C. To automatically refresh the token without any scripting
D. To reuse the token across multiple requests without re-authenticating each time

Solution

  1. Step 1: Understand token reuse in Postman

    Storing a token in an environment variable allows multiple requests to access it easily without needing to get a new token each time.
  2. Step 2: Evaluate other options

    Making the token visible to all users or automatic refresh without scripting is not true by default. Encryption is not automatic either.
  3. Final Answer:

    To reuse the token across multiple requests without re-authenticating each time -> Option D
  4. Quick Check:

    Token reuse = B [OK]
Hint: Tokens stored in variables enable reuse across requests [OK]
Common Mistakes:
  • Thinking tokens auto-refresh without scripts
  • Assuming variables encrypt tokens automatically
  • Believing tokens are shared with all users by default
2. Which of the following is the correct way to set a token value to an environment variable in Postman test script?
easy
A. pm.environment.set('token', response.token);
B. pm.setEnvironmentVariable('token', response.token);
C. pm.environment.token = response.token;
D. pm.variables.set('token', response.token);

Solution

  1. Step 1: Identify the current Postman syntax for setting environment variables

    The correct method is pm.environment.set('variableName', value) in Postman scripts.
  2. Step 2: Check other options for correctness

    pm.setEnvironmentVariable is deprecated, direct assignment is invalid, and pm.variables.set sets local variables, not environment variables.
  3. Final Answer:

    pm.environment.set('token', response.token); -> Option A
  4. Quick Check:

    Use pm.environment.set() to set env variables [OK]
Hint: Use pm.environment.set('name', value) to set env variables [OK]
Common Mistakes:
  • Using deprecated pm.setEnvironmentVariable method
  • Trying to assign variables directly like pm.environment.token
  • Confusing local and environment variables
3. Given this Postman test script snippet after a login request:
let jsonData = pm.response.json();
pm.environment.set('authToken', jsonData.token);

What will be the value of {{authToken}} in the next request if the response JSON is {"token": "abc123"}?
medium
A. null
B. undefined
C. "abc123"
D. pm.response.json()

Solution

  1. Step 1: Extract token from response JSON

    The script gets the token value "abc123" from the response JSON using pm.response.json().token.
  2. Step 2: Set environment variable 'authToken'

    The token value "abc123" is stored in the environment variable 'authToken' using pm.environment.set.
  3. Final Answer:

    "abc123" -> Option C
  4. Quick Check:

    Stored token = "abc123" [OK]
Hint: Stored token equals JSON token value from response [OK]
Common Mistakes:
  • Assuming variable is undefined if not explicitly declared
  • Confusing variable name with function call
  • Expecting null instead of actual token string
4. You wrote this test script to save a token:
let jsonData = pm.response.json();
pm.environment.set('token', jsonData.authToken);

But the token is not saved. What is the most likely reason?
medium
A. You must use pm.variables.set instead
B. The response JSON does not have a key named 'authToken'
C. pm.environment.set is deprecated and does not work
D. Tokens cannot be saved in environment variables

Solution

  1. Step 1: Check the JSON key used in script

    The script tries to access jsonData.authToken, so the response must have that key.
  2. Step 2: Verify if the response JSON contains 'authToken'

    If the response uses a different key like 'token', jsonData.authToken will be undefined and nothing is saved.
  3. Final Answer:

    The response JSON does not have a key named 'authToken' -> Option B
  4. Quick Check:

    Key mismatch causes undefined token [OK]
Hint: Check JSON key names match exactly in script [OK]
Common Mistakes:
  • Assuming pm.environment.set is deprecated
  • Using pm.variables.set for environment variables
  • Believing tokens can't be saved in environment variables
5. You want to automatically refresh an expired token in Postman by chaining requests. Which approach correctly manages the token variable for reuse?
hard
A. Use a pre-request script in all requests to check token expiry and request a new token if expired, then update the environment variable
B. Manually update the token variable in Postman UI before each request
C. Store the token in a global variable and never update it
D. Hardcode the token in the request headers and do not use variables

Solution

  1. Step 1: Understand token expiry handling

    Tokens expire, so scripts must check expiry and refresh tokens automatically to avoid failures.
  2. Step 2: Use pre-request scripts to automate token refresh

    Pre-request scripts can check if the token is expired and call the authentication endpoint to get a new token, then update the environment variable.
  3. Step 3: Evaluate other options

    Manual updates are error-prone, global variables without updates cause failures, and hardcoding tokens is insecure and inflexible.
  4. Final Answer:

    Use a pre-request script in all requests to check token expiry and request a new token if expired, then update the environment variable -> Option A
  5. Quick Check:

    Automate token refresh with pre-request scripts [OK]
Hint: Automate token refresh in pre-request scripts [OK]
Common Mistakes:
  • Relying on manual token updates
  • Using global variables without refresh logic
  • Hardcoding tokens in requests