Skip to content

How To Use Authorization Bearer In Postman

API Testing Blog

Understanding Authorization Bearer in Postman

Authorization Bearer is a common authentication scheme used in REST APIs to verify user identity and grant access to protected resources. It’s based on the OAuth 2.0 standard and relies on a token to represent the user’s authorization.

How it works:

  1. Authentication: The user authenticates with the API using credentials (username/password, social login, etc.).
  2. Token Issuance: Upon successful authentication, the API server issues a unique JSON Web Token (JWT) to the user.
  3. Authorization: The user sends the token in the request header with the Authorization field, using the Bearer scheme:
    Authorization: Bearer <token>
  4. Validation: The API server validates the token, checks if it’s still valid, and grants access based on the user’s permissions.

Setting Up Authorization Bearer in Postman

Postman allows you to easily configure and manage authorization bearer tokens for your API requests. Here’s how:

  1. Open Postman: Start Postman and create a new request.
  2. Navigate to Authorization Tab: In the request builder, click on the “Authorization” tab.
  3. Select Type: Choose “Bearer Token” as the authorization type.
  4. Enter Token: Paste your Bearer token in the “Token” field.
  5. Save as Environment Variable (Optional): For better organization and reusability, you can store the token as an environment variable. This allows you to easily switch between different tokens or use them in multiple requests.

Example: Using Bearer Token for Authentication

Let’s consider a hypothetical API that uses Bearer Token authentication:

API Endpoint: https://api.example.com/users Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjg2NjY0MDAwfQ.r6yX157gT0gL27J5s0tY3E3eQ4m_WvW98M2d69jW64

Steps:

  1. Create a new request: Click the “New” button in Postman and choose “Request.”
  2. Set Request Details:
    • In the “Request URL” field, type: https://api.example.com/users
    • Select the “GET” method.
  3. Add Bearer Token:
    • Go to the “Authorization” tab in the request builder.
    • Select “Bearer Token” as the type.
    • Paste the token in the “Token” field: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjg2NjY0MDAwfQ.r6yX157gT0gL27J5s0tY3E3eQ4m_WvW98M2d69jW64
  4. Send Request: Click the “Send” button to execute the request.

Postman will now send the request with the Bearer token included in the Authorization header:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjg2NjY0MDAwfQ.r6yX157gT0gL27J5s0tY3E3eQ4m_WvW98M2d69jW64

Using Environment Variables for Bearer Tokens

Storing tokens as environment variables offers several benefits:

  • Organization and Reusability: You can manage multiple tokens easily and use them across different requests.
  • Security: Concealing sensitive data like tokens in a separate file prevents hardcoding them directly in the request.
  • Flexibility: You can update or change tokens without modifying the individual requests.

How to Set Up Environment Variables:

  1. Create Environment: Go to “Environments” in Postman and create a new environment (e.g., “Test Environment”).
  2. Add Variable: In the environment editor, click “Add” and provide a name (e.g., “authToken”) and the token value.
  3. Use Variable in Request: In the request builder, replace the token field with {{authToken}}. This will dynamically fetch the token from the environment variable.
  4. Switch Environments: You can easily switch between different environments (e.g., “Test Environment” or “Production Environment”) to use different tokens based on the context.

Example: Using Environment Variables for Bearer Tokens

Step 1: Create Environment Variable

  • Open Postman and go to “Environments.”
  • Click “Add” and create an environment named “Test Environment.”
  • In the environment editor, click “Add.”
  • Enter “authToken” for the variable name and the actual token for the value: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNjg2NjY0MDAwfQ.r6yX157gT0gL27J5s0tY3E3eQ4m_WvW98M2d69jW64.
  • Click “Save” to save the environment.

Step 2: Use Environment Variable in Request

  • Create a new request as before, following steps 1-3.
  • In the “Authorization” tab, select “Bearer Token.”
  • Replace the token field with the environment variable: {{authToken}}.
  • Send the request and verify that it successfully fetches the user data, now using the token stored in the environment variable.

Dynamic Bearer Token Generation

Some APIs require the token to be generated dynamically. In such cases, you can use Postman’s scripting capabilities to obtain the token before each request.

Example: Obtaining Token from a Dynamic API Endpoint

Scenario:

  • Your API has a separate endpoint for token generation (https://api.example.com/token).
  • This endpoint expects credentials (username, password) as request body in JSON format.
  • The endpoint returns a JSON response containing the newly generated token.

Postman Steps:

  1. Create a Request for Token Generation:
    • Create a new request in Postman (e.g., “Get Token”).
    • Set the URL to https://api.example.com/token.
    • Choose the “POST” method.
    • Add the authorization information to get the initial token (like basic auth).
    • In the “Body” tab, set the content type to “application/json”.
    • Add your credentials in the request body as JSON:
      {
      "username": "yourusername",
      "password": "yourpassword"
      }
  2. Add a Pre-request Script:
    • Navigate to the “Pre-request Script” tab.
    • Write the following script to extract the token from the response:
      const response = pm.sendRequest("Get Token");
      const token = response.json().token;
      pm.environment.set("authToken", token);
  3. Use Dynamic Token in Authentication:
    • Create another request (e.g., “Access Users”) for the API endpoint that requires authorization (https://api.example.com/users).
    • Set the authorization type to “Bearer Token” and use the environment variable in the token field: {{authToken}}.
    • Send the “Get Token” request first to generate the token.
    • Then send the “Access Users” request to access the secured resources.

Explanation:

  • The pre-request script executes before every “Access Users” request.
  • It sends a request to the “/token” endpoint to retrieve the token.
  • The response.json().token line extracts the token value from the JSON response.
  • The pm.environment.set() function stores the retrieved token as the environment variable “authToken.”
  • The “Access Users” request then uses the value of “authToken” for Bearer authorization.

Handling Token Expiration

Real-world APIs usually have token expiration. To handle this:

  1. Check Expiration: The API response may contain information about the token’s expiration (usually in JWT format).
  2. Renew Token: If the token is about to expire, use a pre-request script to automatically refresh the token by making a request to a specific endpoint (e.g., /refresh) and update the environment variable.

Example: Handling Token Expiration in Pre-request Script:

// Get token info
const tokenInfo = pm.response.json();
// Check expiration time
const expirationTimestamp = Date.parse(tokenInfo.exp);
const currentTime = new Date();
// Renew if token is about to expire in next 1 minute (60000 milliseconds)
if (currentTime.getTime() + 60000 >= expirationTimestamp) {
console.log("Token is about to expire, refreshing...");
const refreshResponse = pm.sendRequest("Refresh Token");
const newToken = refreshResponse.json().token;
pm.environment.set("authToken", newToken);
}

Key Points to Remember

  • Security: Never hardcode Bearer tokens in your Postman requests. Always use environment variables or dynamic generation techniques.
  • Scope and Permissions: Bearer tokens often have different scopes or permissions associated with them. This controls which resources the token holder can access.
  • Expiration: Be aware of token expiration and implement logic to handle expiration gracefully, such as refreshing tokens.
  • Authentication: The method you use to initially obtain the Bearer token (e.g., basic auth, OAuth flow) will depend on the specific API you are working with.

By following these best practices, you can efficiently authenticate requests in Postman and access protected resources securely.

API Testing Blog