0
0
Postmantesting~8 mins

Token management in variables in Postman - Framework Patterns

Choose your learning style9 modes available
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.