> ## Documentation Index
> Fetch the complete documentation index at: https://docs.auth-agent.com/llms.txt
> Use this file to discover all available pages before exploring further.

# POST /token

> Exchange authorization code or refresh token for access tokens

## Overview

The token endpoint is used to exchange an authorization code for access tokens, or to refresh an expired access token using a refresh token.

```
POST https://api.auth-agent.com/token
```

## Request Body

Content-Type: `application/json`

### Authorization Code Grant

**grant\_type** `string` *required*

Must be `authorization_code` for code exchange

**code** `string` *required*

The authorization code received from the `/authorize` endpoint

**code\_verifier** `string` *required*

The PKCE code verifier that was used to generate the code challenge

**redirect\_uri** `string` *required*

The same redirect URI used in the authorization request

**client\_id** `string` *required*

Your OAuth client ID

**client\_secret** `string` *required*

Your OAuth client secret

### Refresh Token Grant

**grant\_type** `string` *required*

Must be `refresh_token` for token refresh

**refresh\_token** `string` *required*

The refresh token received in a previous token response

**client\_id** `string` *required*

Your OAuth client ID

**client\_secret** `string` *required*

Your OAuth client secret

## Response

### Success (200 OK)

```json theme={null}
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "rt_abc123xyz...",
  "scope": "openid email profile"
}
```

**access\_token** `string`

JWT access token used to authenticate API requests. Valid for 1 hour.

**token\_type** `string`

Always `Bearer`

**expires\_in** `number`

Time in seconds until the access token expires (3600 = 1 hour)

**refresh\_token** `string`

Refresh token used to obtain new access tokens. Valid for 30 days.

> [!WARNING]
>
> Refresh tokens are automatically rotated. The old refresh token is revoked when you use it, and a new one is issued.

**scope** `string`

Space-separated list of granted scopes

### Error (400 / 401)

```json theme={null}
{
  "error": "invalid_grant",
  "error_description": "Invalid or expired authorization code"
}
```

## Error Codes

| Error Code | HTTP Status | Description |
| - | - | - |
| `unsupported_grant_type` | 400 | Grant type must be `authorization_code` or `refresh_token` |
| `invalid_request` | 400 | Missing required parameters |
| `invalid_client` | 401 | Invalid client credentials |
| `invalid_grant` | 400 | Invalid, expired, or revoked authorization code/refresh token |
| `server_error` | 500 | Internal server error |

## Example Requests

```typescript Authorization Code Exchange theme={null}
// After receiving authorization code in callback
const tokenResponse = await fetch('https://api.auth-agent.com/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    grant_type: 'authorization_code',
    code: authorizationCode,
    code_verifier: sessionStorage.getItem('code_verifier'),
    redirect_uri: 'https://yourwebsite.com/api/auth/callback',
    client_id: process.env.AUTH_AGENT_CLIENT_ID,
    client_secret: process.env.AUTH_AGENT_CLIENT_SECRET,
  }),
});

const tokens = await tokenResponse.json();

// Store tokens securely
// tokens.access_token - Use for API requests
// tokens.refresh_token - Use to get new access tokens
```

```typescript Refresh Token theme={null}
// When access token expires, use refresh token to get new tokens
const tokenResponse = await fetch('https://api.auth-agent.com/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    grant_type: 'refresh_token',
    refresh_token: storedRefreshToken,
    client_id: process.env.AUTH_AGENT_CLIENT_ID,
    client_secret: process.env.AUTH_AGENT_CLIENT_SECRET,
  }),
});

const newTokens = await tokenResponse.json();

// Update stored tokens
// Old refresh token is now invalid - use newTokens.refresh_token
```

```typescript Express Example theme={null}
app.get('/api/auth/callback', async (req, res) => {
  const { code } = req.query;
  const codeVerifier = req.session.codeVerifier;

  try {
    const tokenResponse = await fetch('https://api.auth-agent.com/token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        grant_type: 'authorization_code',
        code,
        code_verifier: codeVerifier,
        redirect_uri: `${process.env.BASE_URL}/api/auth/callback`,
        client_id: process.env.AUTH_AGENT_CLIENT_ID,
        client_secret: process.env.AUTH_AGENT_CLIENT_SECRET,
      }),
    });

    const tokens = await tokenResponse.json();

    // Store in session or database
    req.session.tokens = tokens;

    res.redirect('/dashboard');
  } catch (error) {
    res.redirect('/auth/error');
  }
});
```

```python Flask Example theme={null}
@app.route('/api/auth/callback')
def callback():
    code = request.args.get('code')
    code_verifier = session.get('code_verifier')

    response = requests.post(
        'https://api.auth-agent.com/token',
        json={
            'grant_type': 'authorization_code',
            'code': code,
            'code_verifier': code_verifier,
            'redirect_uri': f"{os.environ['BASE_URL']}/api/auth/callback",
            'client_id': os.environ['AUTH_AGENT_CLIENT_ID'],
            'client_secret': os.environ['AUTH_AGENT_CLIENT_SECRET'],
        }
    )

    tokens = response.json()

    # Store in session
    session['tokens'] = tokens

    return redirect('/dashboard')
```

## Token Lifecycle

**1. Authorization Code Exchange**

Exchange the authorization code for initial access and refresh tokens. Authorization codes expire after 10 minutes.

**2. Use Access Token**

Use the access token to make authenticated API requests. Access tokens are valid for 1 hour.

**3. Refresh When Expired**

When the access token expires, use the refresh token to get new tokens. Refresh tokens are valid for 30 days.

**4. Automatic Rotation**

Each refresh generates new access and refresh tokens. The old refresh token is automatically revoked.

## Access Token Structure

Access tokens are JWTs (JSON Web Tokens) with the following structure:

### Header

```json theme={null}
{
  "alg": "HS256",
  "typ": "JWT"
}
```

### Payload

```json theme={null}
{
  "sub": "agent_abc123",
  "iss": "https://api.auth-agent.com",
  "iat": 1234567890,
  "exp": 1234571490,
  "client_id": "client_xyz789",
  "model": "gpt-4",
  "scope": "openid email profile"
}
```

| Claim | Description |
| - | - |
| `sub` | Agent ID (subject) |
| `iss` | Issuer (Auth Agent API URL) |
| `iat` | Issued at timestamp |
| `exp` | Expiration timestamp |
| `client_id` | OAuth client ID |
| `model` | AI model used by the agent |
| `scope` | Granted scopes |

## Token Storage Best Practices

> [accordion] Server-Side Applications
>
> Store tokens in secure, HTTP-only cookies or server-side sessions. Never expose client secrets in client-side code.
>
> ```typescript theme={null}
> // Set secure HTTP-only cookie
> res.cookie('auth_tokens', JSON.stringify(tokens), {
>   httpOnly: true,
>   secure: true,
>   sameSite: 'lax',
>   maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
> });
> ```

> [accordion] Token Refresh Strategy
>
> Implement proactive token refresh before expiration:
>
> ```typescript theme={null}
> async function getValidAccessToken() {
>   const tokens = getStoredTokens();
>   const decoded = jwt.decode(tokens.access_token);
>
>   // Refresh if expires in less than 5 minutes
>   const expiresIn = decoded.exp - Date.now() / 1000;
>   if (expiresIn < 300) {
>     return await refreshAccessToken(tokens.refresh_token);
>   }
>
>   return tokens.access_token;
> }
> ```

> [accordion] Handle Refresh Token Rotation
>
> Always update stored tokens after refresh:
>
> ```typescript theme={null}
> async function refreshAccessToken(refreshToken: string) {
>   const response = await fetch('https://api.auth-agent.com/token', {
>     method: 'POST',
>     headers: { 'Content-Type': 'application/json' },
>     body: JSON.stringify({
>       grant_type: 'refresh_token',
>       refresh_token: refreshToken,
>       client_id: process.env.AUTH_AGENT_CLIENT_ID,
>       client_secret: process.env.AUTH_AGENT_CLIENT_SECRET,
>     }),
>   });
>
>   const newTokens = await response.json();
>
>   // IMPORTANT: Update stored tokens with new refresh token
>   updateStoredTokens(newTokens);
>
>   return newTokens.access_token;
> }
> ```

## Security Considerations

> [!WARNING]
>
> **Never expose client secrets** in client-side code. Token exchange should always happen server-side.

> [!WARNING]
>
> **Refresh token rotation** - Old refresh tokens are revoked immediately upon use. Always store the new refresh token from the response.

> [!NOTE]
>
> **PKCE validation** - The code\_verifier must match the code\_challenge used in the authorization request, or the token exchange will fail.

## Next Steps

> [card] [Get User Info](https://docs.auth-agent.com/api-reference/oauth/userinfo.md)
>
> GET /userinfo - Retrieve user information

> [card] [Introspect Token](https://docs.auth-agent.com/api-reference/oauth/introspect.md)
>
> POST /introspect - Validate and inspect tokens

> [card] [Revoke Token](https://docs.auth-agent.com/api-reference/oauth/revoke.md)
>
> POST /revoke - Revoke access or refresh tokens

> [card] [Integration Guide](https://docs.auth-agent.com/guides/integration-scenarios.md)
>
> Learn about integration patterns


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.