# What is a Bearer Token? Understanding API Authentication

### Quick answer

Bearer tokens authenticate API requests by granting access to whoever possesses the token, passed in the Authorization header as `Authorization: Bearer <token>`. They're commonly used with OAuth 2.0 and provide a simple way to secure APIs without requiring complex cryptographic signing for each request.

This guide explains how bearer tokens work in practice, when to use them, and how to test authenticated requests during API development.

[Try Postman today →](<https://identity.getpostman.com/signup >)

 

## What is a bearer token?

A bearer token is a security token that grants access to whoever holds it. The name "bearer" means that anyone with the token can access protected resources without additional proof of identity. Think of it like a concert ticket: whoever holds it can enter.

Bearer tokens are defined by RFC 6750 and are most commonly used with OAuth 2.0. When a client needs to access protected resources, it includes the bearer token in the Authorization header of each HTTP request. The server validates the token and grants access if it’s valid.

## How bearer tokens work

The typical flow:

1. Client authenticates with credentials (username/password or OAuth flow).
2. Server generates and returns a bearer token.
3. Client stores the token securely.
4. Client includes token in Authorization header for each request.
5. Server validates token and grants or denies access.
6. Token expires after predetermined time.
 
### Bearer token format

Bearer tokens follow a specific format in HTTP headers:

 ```
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</code
```

 The format consists of the scheme identifier "Bearer", a space, and the token value. The token itself can be a random string or a structured format, such as JSON Web Token (JWT). ## Example: Using bearer tokens

 Here's what a complete API request with bearer token authentication looks like. First, authenticate to receive a bearer token: ```
POST /api/auth/login HTTP/1.1
Host: api.example.com
Content-Type: application/json

{
  "username": "developer@example.com",
  "password": "secure_password"
}

```

 The server responds with a token: ```
HTTP/1.1 200 OK
Content-Type: application/json

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600
}
</code
```

 Now use the bearer token to access protected resources: ```
GET /api/users/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json

```

 The server validates the token and returns the requested data. ## Types of bearer tokens

Bearer tokens come in different formats, each with specific characteristics.

### Opaque tokens

Opaque tokens are random strings with no meaning to clients. The server maintains a database that maps tokens to user information and permissions. They're simple to implement and easy to revoke, but they require server-side storage.

### JSON Web Tokens (JWT)

JWTs are structured tokens that encode information directly within the token itself.

The three parts of a JWT include:

1. Header
2. Payload
3. Signature
 
JWTs are self-contained, cryptographically signed, and enable stateless authentication, which makes them ideal for microservices and distributed systems.

### Refresh tokens

Refresh tokens are long-lived bearer tokens used specifically to get new access tokens without requiring re-authentication. They're commonly used in mobile and single-page applications to maintain persistent sessions.

## Bearer tokens vs API keys

Understanding the difference between bearer tokens and API keys helps you choose the right authentication method.

 | **Authentication type** | **Bearer token** | **API key** |
|---|---|---|
| **Purpose** | User or session authentication | Application identification |
| **Lifespan** | Temporary (minutes to hours) | Long-lived (months to years) |
| **Revocation** | Expires automatically | Manual revocation required |
| **User context** | Tied to a specific user | Tied to the application |

 Use bearer tokens when authenticating individual users, implementing OAuth 2.0, or requiring automatic expiration. Use API keys to identify applications, manage rate limits, or facilitate simple server-to-server communication. ## Security best practices

Bearer tokens require careful handling to prevent security vulnerabilities.

### Always use HTTPS

Bearer tokens must be transmitted over HTTPS. Without encryption, tokens can be intercepted and used by attackers.

### Implement token expiration

Short-lived tokens reduce risk if compromised. Typical access token lifespans range from 5 minutes to 1 hour. Use refresh tokens for longer sessions without repeatedly exposing credentials.

### Secure token storage

Never log tokens in console, include them in URLs, or store them carelessly in localStorage. Instead:

- Use HTTP-only cookies when appropriate
- Store in-memory for single-page applications
- Use secure device storage for mobile apps
- Clear tokens on logout
 
### Validate tokens properly

Servers must validate tokens thoroughly before granting access:

- Verify signature (for JWTs)
- Check expiration time
- Validate issuer and audience
- Check revocation status if implemented
 
## Testing bearer tokens in Postman

Postman gives you a simple way to test APIs that use bearer token authentication.

### Basic setup

1. Open your request in Postman.
2. Navigate to the **Authorization** tab.
3. Select **Bearer Token** from the **Type** dropdown.
4. Enter your token in the **Token** field.
5. Click **Send**.
 
Postman automatically formats the Authorization header correctly.

### Using variables

Store tokens as environment or collection variables for easier management:

1. Create an environment variable called `bearer_token`.
2. In the **Authorization** tab, use `{{bearer_token}}`.
3. Update the variable value when you receive new tokens.
 
For collection-level authentication, configure it once in the collection settings so that all requests inherit the authentication.

### Automating token refresh

Use Postman's pre-request scripts to automatically obtain fresh tokens:

 ```
const tokenExpiry = pm.environment.get('token_expiry');
const now = Date.now();

if (!tokenExpiry || now >= tokenExpiry) {
    pm.sendRequest({
        url: 'https://api.example.com/auth/token',
        method: 'POST',
        header: {'Content-Type': 'application/json'},
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                client_id: pm.environment.get('client_id'),
                client_secret: pm.environment.get('client_secret')
            })
        }
    }, (err, response) => {
        const jsonData = response.json();
        pm.environment.set('bearer_token', jsonData.access_token);
        pm.environment.set('token_expiry', now + (jsonData.expires_in * 1000));
    });
}
</code
```

## Common mistakes to avoid

### Missing the "Bearer" prefix

 The Authorization header requires the scheme identifier: **Wrong:** `Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...`### Using tokens over HTTP

 Never transmit bearer tokens over unencrypted connections. Always use HTTPS. ### Storing tokens insecurely

 Avoid logging tokens or storing them without proper security measures. Use appropriate storage mechanisms for your platform and always clear tokens on logout. ### Ignoring token expiration

 Always check token expiration and handle expired tokens gracefully by implementing refresh logic. ## Troubleshooting

### 401 Unauthorized errors

When you receive a 401 status code, the token is invalid or missing. Common causes include expired tokens, missing "Bearer" prefix, or incorrect token format. Verify the token format and obtain a fresh token if it’s expired.

### 403 Forbidden errors

A 403 status indicates the token is valid but lacks necessary permissions. Verify that the token scopes match the resource requirements and check the user’s permissions in the system.

### Token not being accepted

If the server consistently rejects valid tokens, verify that you've included the "Bearer" prefix, there are no extra spaces, the header name is exactly "Authorization", and you're using HTTPS.

### Quick reference

 | Question | Answer |
|---|---|
| What is a bearer token? | A security token that grants access to whoever possesses it. |
| How is it formatted? | `Authorization: Bearer <token> ` in the HTTP header. |
| Bearer token vs API key? | Bearer tokens are temporary and user-specific; API keys are long-lived and application-specific. |
| Are they secure? | Yes, when used over HTTPS with proper expiration and storage. |
| How long do they last? | Typically 5 minutes to 1 hour for access tokens.. |
| Can they be revoked? | Yes, through revocation lists or token versioning. |