---
llm-context: developer-guide
category: authentication
title: OAuth Token Refresh
difficulty: beginner
time: 8 minutes
format: markdown
updated: 
---


# OAuth Token Refresh

Access tokens expire after 1 hour. This guide shows you how to automatically refresh them to keep your integration running smoothly.

## Why Do Tokens Expire?

**Security.** Short-lived access tokens limit damage if they&#39;re stolen. Even if someone intercepts your access token, it only works for 1 hour.

OAuth 2.0 encourages short-lived access tokens and long-lived refresh tokens, and leaves the lifetimes to each implementation. The reasons:

- **Token compromise:** a short-lived access token limits how long an attacker can use a stolen one.
- **Least privilege:** access is granted for the shortest time it is needed.
- **Rotation:** short lifetimes mean tokens are replaced often, which makes a stolen one harder to misuse.
- **Audit and revoke:** short-lived tokens are easier to audit, and to revoke one at a time.
- **Refresh tokens:** a new access token is obtained with a refresh token, and only the app the refresh token was issued to can use it: the refresh request carries that app&#39;s client credentials.

The [OAuth 2.0 Security Best Current Practice](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics) and [oauth.com&#39;s guide to refreshing an access token](https://www.oauth.com/oauth2-servers/making-authenticated-requests/refreshing-an-access-token/) cover the background.

**Two types of tokens:**

| Token Type | Lifespan | Purpose |
|------------|----------|---------|
| Access Token | 1 hour | Make API calls |
| Refresh Token | No fixed expiry; works once | Get new access tokens |

## How Long a Refresh Token Lasts

A refresh token has no fixed expiry. It works once: each refresh returns a new access token and a new refresh token, and revokes the old pair straight away.

A refresh token stops working when:

- **it has been used** to refresh, even if your app never received the response;
- **your app revokes it,** or the access token it was issued with, at `POST /oauth/revoke`;
- **the user removes your app&#39;s access** in their DoorFlow settings;
- **DoorFlow support revokes all of the user&#39;s tokens;**
- **the user, or your OAuth application, is deleted.**

Any of these makes the next refresh fail with `invalid_grant`, and the user has to authorize your app again.

Think of it like a hotel key card:
- **Access token** = Your room key (expires when you check out)
- **Refresh token** = Your ID at the front desk (get a new room key anytime)

## What Happens When Tokens Expire

```mermaid
sequenceDiagram
    participant App as Your Application
    participant API as DoorFlow API

    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Authorization: Bearer [access_token]

    Note over API: Token expired!

    API--&gt;&gt;App: 401 Unauthorized&lt;br/&gt;&quot;The access token expired&quot;

    Note over App: Need to refresh the token
```

When your access token expires, the API returns **401 Unauthorized**. This is your signal to refresh.

## The Token Refresh Flow

Here&#39;s the complete process when a token expires:

```mermaid
sequenceDiagram
    participant App as Your Application
    participant API as DoorFlow API
    participant DB as Your Database

    Note over App,DB: 1. Access token has expired

    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Authorization: Bearer [expired_token]
    API--&gt;&gt;App: 401 Unauthorized

    Note over App: 2. Get refresh token from storage

    App-&gt;&gt;DB: Get refresh_token
    DB--&gt;&gt;App: refresh_token

    Note over App: 3. Request new tokens

    App-&gt;&gt;API: POST /oauth/token&lt;br/&gt;grant_type=refresh_token&lt;br/&gt;refresh_token=...&lt;br/&gt;client_id=...&lt;br/&gt;client_secret=...

    Note over API: Validates refresh token

    API--&gt;&gt;App: 200 OK&lt;br/&gt;New access_token&lt;br/&gt;New refresh_token

    Note over App: 4. Store BOTH new tokens

    App-&gt;&gt;DB: Store new access_token&lt;br/&gt;Store new refresh_token

    Note over App: 5. Retry original request

    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Authorization: Bearer [new_token]
    API--&gt;&gt;App: 200 OK&lt;br/&gt;People data
```

## How to Refresh a Token

**Request:**
```bash
curl -X POST &quot;https://api.doorflow.com/oauth/token&quot; \
  -H &quot;Content-Type: application/x-www-form-urlencoded&quot; \
  -d &quot;grant_type=refresh_token&quot; \
  -d &quot;refresh_token=YOUR_REFRESH_TOKEN&quot; \
  -d &quot;client_id=YOUR_CLIENT_ID&quot; \
  -d &quot;client_secret=YOUR_CLIENT_SECRET&quot;
```

**Parameters:**
- `grant_type` - Always &quot;refresh_token&quot;
- `refresh_token` - Your current refresh token (from storage)
- `client_id` - Your OAuth app&#39;s client ID
- `client_secret` - Your OAuth app&#39;s client secret

**Response:**
```json
{
  &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...&quot;,
  &quot;token_type&quot;: &quot;Bearer&quot;,
  &quot;expires_in&quot;: 3600,
  &quot;refresh_token&quot;: &quot;def502003d8f9a7b2c1e4d5f6g7h8i9j0k...&quot;,
  &quot;scope&quot;: &quot;account.person&quot;,
  &quot;created_at&quot;: 1704070800
}
```

**Critical:** You receive BOTH:
- **New access token** - Use this for API calls
- **New refresh token** - Store this and use it for the next refresh

The old refresh token is now invalid. Always use the newest refresh token.

## Implementation Approach 1: Reactive Refresh

**Strategy:** Wait for 401, then refresh and retry.

```mermaid
flowchart TD
    Start([Need to call API]) --&gt; Call[Make API request&lt;br/&gt;with access_token]
    Call --&gt; Check{Response&lt;br/&gt;status?}

    Check --&gt;|200 OK| Success([Return data])
    Check --&gt;|401 Unauthorized| Refresh[Use refresh_token to get&lt;br/&gt;new access_token]
    Check --&gt;|Other error| Error([Handle error])

    Refresh --&gt; Store[Store new access_token&lt;br/&gt;and new refresh_token]
    Store --&gt; Retry[Retry original API request&lt;br/&gt;with new access_token]
    Retry --&gt; Success
```

**When to use:**
- Simpler to implement
- Good for low-traffic integrations
- Acceptable to have occasional failed requests

**Tradeoff:**
- First API call after expiration fails (then succeeds on retry)

## Implementation Approach 2: Proactive Refresh

**Strategy:** Check expiration time before making calls. Refresh early if needed.

```mermaid
flowchart TD
    Start([Need to call API]) --&gt; Load[Load access_token&lt;br/&gt;and expires_at from storage]
    Load --&gt; Check{Token expires&lt;br/&gt;in next&lt;br/&gt;5 minutes?}

    Check --&gt;|Yes| Refresh[Use refresh_token to get&lt;br/&gt;new access_token]
    Check --&gt;|No| UseExisting[Use existing access_token]

    Refresh --&gt; Store[Store new access_token&lt;br/&gt;and new refresh_token]
    Store --&gt; Call[Make API request&lt;br/&gt;with new access_token]

    UseExisting --&gt; Call
    Call --&gt; Success([Return data])
```

**When to use:**
- High-traffic integrations
- User-facing applications (no failed requests)
- Background jobs with strict timing

**Tradeoff:**
- More complex (track expiration time)
- Still need 401 handling as fallback

**How to track expiration:**

When you store tokens, also calculate and store the expiration time:

```json
{
  &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...&quot;,
  &quot;refresh_token&quot;: &quot;def502003d8f9a7b2c1e4d5f6g7h8i9j0k...&quot;,
  &quot;expires_at&quot;: 1704074400
}
```

**Calculation:**
- API returns `expires_in: 3600` (seconds)
- Your code: `expires_at = current_time + 3600`
- Before API calls: Check if `current_time + 300` (5 min buffer) &gt; `expires_at`

## When Token Refresh Fails

Not all refresh attempts succeed. Here&#39;s how to handle failures:

```mermaid
flowchart TD
    Start([Refresh token request]) --&gt; Post[POST /oauth/token]
    Post --&gt; Check{Response&lt;br/&gt;status?}

    Check --&gt;|200 OK| Success[Store new tokens]
    Check --&gt;|400 Bad Request| ParseError{Error type?}

    Success --&gt; Done([Continue with API calls])

    ParseError --&gt;|invalid_grant| InvalidToken[Refresh token already&lt;br/&gt;used or revoked]
    ParseError --&gt;|invalid_client| WrongCreds[Client ID/secret&lt;br/&gt;is incorrect]
    ParseError --&gt;|unauthorized_client| NotAuth[OAuth app settings&lt;br/&gt;problem]

    InvalidToken --&gt; Reauth[Clear stored tokens&lt;br/&gt;Redirect user to&lt;br/&gt;OAuth authorization flow]
    WrongCreds --&gt; FixCreds([Check your&lt;br/&gt;client credentials])
    NotAuth --&gt; CheckSettings([Check OAuth app&lt;br/&gt;configuration])

    Reauth --&gt; End([User must reconnect])
```

**Common errors:**

| Error | Meaning | Solution |
|-------|---------|----------|
| `invalid_grant` | Refresh token already used, or revoked | User must re-authorize your app |
| `invalid_client` | Client ID or secret wrong | Check your OAuth app credentials |
| `unauthorized_client` | OAuth app not authorized for this grant type | Check OAuth app settings in DoorFlow |

**Most common:** `invalid_grant` means the refresh token was already used, or was revoked (see [How Long a Refresh Token Lasts](#how-long-a-refresh-token-lasts)). Retrying cannot help. Clear stored tokens and send the user through OAuth authorization again.

## Things to Watch Out For

Because a refresh token works once, how your app handles a refresh decides whether it keeps its access:

1. **Replace tokens together.** When a refresh succeeds, store the new access token and the new refresh token in one atomic write. The old pair no longer works.
2. **Refresh one at a time.** Two refreshes with the same refresh token cannot both succeed: DoorFlow answers the second with `invalid_grant`. Make sure only one request per user refreshes at once, and let the others wait for its result.
3. **Handle errors.** Check that a refresh response is what you expect before you use it, and log and alert on failures so someone can step in.
4. **Set timeouts.** Give the refresh request a timeout so a hung request does not block your app. If a refresh times out, the old refresh token may already be revoked: the next attempt then fails with `invalid_grant`.
5. **Validate new tokens before use.** Check the new tokens&#39; format and values before they replace the old ones.
6. **Retry with exponential backoff, but not on `invalid_grant`.** Retry a refresh that failed on a network error or a 5xx response, backing off each time so you do not overwhelm the token endpoint. An `invalid_grant` is final.
7. **Log and monitor token operations, never token values.** Log each refresh and its outcome, and alert on errors. Never write an access or refresh token to a log.
8. **Have a manual fallback.** Give support a way to reconnect a user by hand when automated refresh fails, as a last resort.

## Storing Tokens Securely

**Security requirements:**

1. **Encrypt refresh tokens** in your database
2. **Never log tokens** (access or refresh)
3. **Clear tokens on logout**
4. **Use HTTPS only** for all API calls
5. **Store tokens per user** (never share tokens between users)

**What to store:**

```json
{
  &quot;user_id&quot;: 12345,
  &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...&quot;,
  &quot;refresh_token&quot;: &quot;ENCRYPTED:def502003d8f9a7b2c1e4d5f6g7h8i9j0k...&quot;,
  &quot;expires_at&quot;: 1704074400,
  &quot;scope&quot;: &quot;account.person account.channel.readonly&quot;
}
```

**Critical:** Refresh tokens are long-lived and powerful. If someone steals a refresh token, they can access the API indefinitely. Always encrypt them.

## Testing Your Implementation

**How to test token refresh:**

1. **Manually expire a token** in your database:
   - Set `expires_at` to a time in the past
   - Example: `expires_at = current_time - 1000`

2. **Make an API call** - Should trigger your refresh logic

3. **Verify**:
   - API call succeeds
   - New tokens stored in database
   - New `expires_at` is ~1 hour in the future

**Test error handling:**

1. **Test invalid refresh token:**
   - Change the refresh token in your database to `&quot;invalid_token&quot;`
   - Make an API call
   - Verify user is sent through OAuth flow again

2. **Test network errors:**
   - Temporarily break network connection
   - Make an API call
   - Verify appropriate error message shown to user

## Complete Flow Example

Here&#39;s everything together - from initial OAuth through token refresh:

```mermaid
sequenceDiagram
    participant User
    participant App as Your Application
    participant API as DoorFlow API
    participant DB as Your Database

    Note over User,DB: Initial OAuth Authorization

    User-&gt;&gt;App: Clicks &quot;Connect DoorFlow&quot;
    App-&gt;&gt;API: Redirect to /oauth/authorize
    User-&gt;&gt;API: Approves access
    API-&gt;&gt;App: Redirect with code
    App-&gt;&gt;API: POST /oauth/token&lt;br/&gt;(exchange code)
    API--&gt;&gt;App: access_token + refresh_token
    App-&gt;&gt;DB: Store both tokens + expires_at

    Note over User,DB: Making API Calls (token valid)

    App-&gt;&gt;DB: Get access_token
    DB--&gt;&gt;App: access_token
    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Bearer [access_token]
    API--&gt;&gt;App: 200 OK (people data)

    Note over User,DB: 1 Hour Later (token expired)

    App-&gt;&gt;DB: Get access_token
    DB--&gt;&gt;App: access_token (expired)
    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Bearer [expired_token]
    API--&gt;&gt;App: 401 Unauthorized

    Note over App: Token expired - refresh it

    App-&gt;&gt;DB: Get refresh_token
    DB--&gt;&gt;App: refresh_token
    App-&gt;&gt;API: POST /oauth/token&lt;br/&gt;grant_type=refresh_token
    API--&gt;&gt;App: New access_token + refresh_token
    App-&gt;&gt;DB: Store new tokens
    App-&gt;&gt;API: GET /api/3/people&lt;br/&gt;Bearer [new_token]
    API--&gt;&gt;App: 200 OK (people data)
```

## Quick Decision Guide

**Which refresh strategy should I use?**

```mermaid
flowchart TD
    Start{What type of&lt;br/&gt;integration?}

    Start --&gt;|Background job&lt;br/&gt;runs every few hours| Reactive[Use Reactive Refresh&lt;br/&gt;Wait for 401, then refresh]
    Start --&gt;|User-facing web app&lt;br/&gt;Real-time updates| Proactive[Use Proactive Refresh&lt;br/&gt;Check expiration before calls]
    Start --&gt;|Mobile app| Proactive
    Start --&gt;|Webhook handler&lt;br/&gt;Low traffic| Reactive

    Reactive --&gt; Simple[Simpler to implement&lt;br/&gt;Occasional 401 is fine]
    Proactive --&gt; Complex[More complex&lt;br/&gt;No failed requests]
```

**When do I need to re-authorize the user?**

Only when refresh token is invalid:
- User revoked your app&#39;s access
- OAuth app credentials changed
- OAuth app was deleted
- Refresh token manually deleted

Regular expiration of access tokens does NOT require re-authorization.

## Common Mistakes

**1. Not storing the new refresh token**

Each refresh gives you a NEW refresh token. The old one is invalid.

**Wrong:**
- Refresh token → Get new access token
- Store new access token
- Keep using old refresh token ❌

**Right:**
- Refresh token → Get new access token AND new refresh token
- Store BOTH new tokens ✓

**2. Not handling refresh failures**

Refresh can fail. Always have a fallback to re-authorize.

**3. Logging tokens**

Never log access or refresh tokens. Use `[REDACTED]` in logs.

**4. Storing tokens in localStorage (web apps)**

Use secure, httpOnly cookies or server-side sessions. localStorage is vulnerable to XSS attacks.

**5. Sharing tokens between users**

Each user needs their own tokens. Never reuse tokens across different users.

## Quick Reference

**Refresh a token:**
```bash
POST https://api.doorflow.com/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token
refresh_token=YOUR_REFRESH_TOKEN
client_id=YOUR_CLIENT_ID
client_secret=YOUR_CLIENT_SECRET
```

**Response:**
- `access_token` - Use for API calls (1 hour lifetime)
- `refresh_token` - Store for next refresh (replaces old one)
- `expires_in` - 3600 (seconds)

**When to refresh:**
- **Reactive:** When you get 401 Unauthorized
- **Proactive:** 5 minutes before token expires

**What to store:**
- `access_token`
- `refresh_token` (encrypted)
- `expires_at` (current time + expires_in)
- `scope`

**Security rules:**
- Encrypt refresh tokens
- Never log tokens
- HTTPS only
- Clear tokens on logout

## Next Steps

Now that you understand token refresh:

- [OAuth Authorization Flow] - See where refresh tokens come from
- [Choosing the Right Scopes] - Select appropriate permissions
- [Error Handling] - Handle all API error scenarios
- [Common Workflows] - See complete integration examples

