---
title: "API Authentication"
description: "AgentSync APIs use OAuth 2.0 with the Client Credentials grant type for authentication. This guide covers everything you need to know about authenticating with our APIs."
url: "https://internal-developer-portal.agentsync.io/api-authentication"
image: "https://internal-developer-portal.agentsync.io/_og/d/c_Ocean.takumi,title_API+Authentication,description_AgentSync+APIs+use+OAuth+2.0+with+the+Client+Credentials+grant+type+for+authentication.+This+guide+covers+everything+you+need+to+know+about+authenticating+with+our+APIs.,props_eyJ0aGVtZSI6eyJjb2xvcnMiOnt9fX0,p_Ii9hcGktYXV0aGVudGljYXRpb24i,s_mbzeI0-Xlj89Ocv9.png"
---

# API Authentication

AgentSync APIs use OAuth 2.0 with the Client Credentials grant type for authentication. This guide covers everything you need to know about authenticating with our APIs.

## [Overview](#overview)

All API requests must include a valid access token in the `Authorization` header:

```text
Authorization: Bearer <access_token>
```

## [OAuth 2.0 Client Credentials Flow](#oauth-20-client-credentials-flow)

### [Step 1: Obtain Credentials](#step-1-obtain-credentials)

Request API credentials from the DevOps team. You'll receive:

-   **Client ID** - Your application's unique identifier
-   **Client Secret** - Your application's secret key (keep this secure!)

### [Step 2: Request an Access Token](#step-2-request-an-access-token)

Make a POST request to the token endpoint:

**Endpoint:** `POST https://auth.agentsync.io/oauth/token`

**Request:**

```bash
curl -X POST https://auth.agentsync.io/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=YOUR_CLIENT_ID" \
  -d "client_secret=YOUR_CLIENT_SECRET"
```

**Response:**

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### [Step 3: Use the Access Token](#step-3-use-the-access-token)

Include the token in the `Authorization` header of all API requests:

```bash
curl -X GET https://api.agentsync.io/v1/resource \
  -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json"
```

## [Token Management](#token-management)

### [Token Expiration](#token-expiration)

-   Access tokens expire after **1 hour** (3600 seconds)
-   Check the `expires_in` field in the token response
-   Implement token refresh before expiration

### [Token Refresh Strategy](#token-refresh-strategy)

**Best Practice:** Request a new token when the current token has less than 5 minutes remaining.

```python
import time
import requests

class TokenManager:
    def __init__(self, client_id, client_secret, auth_url):
        self.client_id = client_id
        self.client_secret = client_secret
        self.auth_url = auth_url
        self.token = None
        self.expires_at = 0

    def get_token(self):
        # Refresh if token expires in less than 5 minutes
        if time.time() > self.expires_at - 300:
            self._refresh_token()
        return self.token

    def _refresh_token(self):
        response = requests.post(
            self.auth_url,
            data={
                "grant_type": "client_credentials",
                "client_id": self.client_id,
                "client_secret": self.client_secret
            }
        )
        response.raise_for_status()
        data = response.json()
        self.token = data["access_token"]
        self.expires_at = time.time() + data["expires_in"]
```

## [Authentication Endpoints](#authentication-endpoints)

| Environment | Token Endpoint                                |
| :---------- | :-------------------------------------------- |
| Development | https://auth.dev.agentsync.io/oauth/token     |
| Test        | https://auth.test.agentsync.io/oauth/token    |
| Sandbox     | https://auth.sandbox.agentsync.io/oauth/token |
| Production  | https://auth.agentsync.io/oauth/token         |

## [Security Best Practices](#security-best-practices)

### [Do](#do)

-   Store credentials securely (environment variables, secrets manager)
-   Implement token refresh before expiration
-   Use HTTPS for all API communications
-   Rotate credentials periodically
-   Monitor for unauthorized access attempts

### [Don't](#dont)

-   Commit credentials to version control
-   Share credentials between applications
-   Log access tokens or credentials
-   Store tokens in client-side storage
-   Use long-lived tokens without refresh

## [Error Handling](#error-handling)

### [Common Authentication Errors](#common-authentication-errors)

| Status Code | Error               | Description                      |
| :---------- | :------------------ | :------------------------------- |
| 401         | invalid_token       | Token is expired or invalid      |
| 401         | invalid_client      | Client ID or secret is incorrect |
| 403         | insufficient_scope  | Token lacks required permissions |
| 429         | rate_limit_exceeded | Too many token requests          |

### [Example Error Response](#example-error-response)

```json
{
  "error": "invalid_token",
  "error_description": "The access token is expired or invalid"
}
```

### [Handling Expired Tokens](#handling-expired-tokens)

```python
def make_api_call(url, token_manager):
    token = token_manager.get_token()
    headers = {"Authorization": f"Bearer {token}"}

    response = requests.get(url, headers=headers)

    if response.status_code == 401:
        # Token might be expired, force refresh and retry
        token_manager._refresh_token()
        token = token_manager.get_token()
        headers = {"Authorization": f"Bearer {token}"}
        response = requests.get(url, headers=headers)

    return response
```

## [Troubleshooting](#troubleshooting)

### ["invalid\_client" Error](#invalid_client-error)

-   Verify your client ID and secret are correct
-   Check you're using the right environment's auth URL
-   Ensure credentials haven't been rotated

### ["invalid\_token" Error](#invalid_token-error)

-   Token may be expired - request a new one
-   Verify you're using the correct environment
-   Check the token hasn't been revoked

### [Connection Errors](#connection-errors)

-   Verify network connectivity to auth servers
-   Check firewall rules allow outbound HTTPS
-   Ensure VPN is connected (for internal environments)

---

**Need help with authentication?** Contact `#devops-support` on Slack.