Documentation

Docs
/
Api Authentication

API Authentication

How to authenticate with the AgentHub API using device flow

API Authentication

AgentHub uses API keys for authentication. API keys are generated using GitHub's device flow, which provides secure authentication for CLI tools, scripts, and applications.

Authentication Method

AgentHub uses API Keys only for programmatic access. These keys are generated through GitHub's device flow authentication process.

Generating API Keys

API keys are generated using GitHub's device flow authentication. This is the only way to authenticate with the AgentHub API.

Step 1: Initiate Device Flow

Start the authentication process:

curl -X POST https://prod-agent-hosting-api.useagenthub.com/auth/device/initiate \
  -H "Content-Type: application/json"

Response:

{
  "device_code": "123abc....",
  "user_code": "XXXX-XXXX",
  "verification_uri": "https://github.com/login/device",
  "expires_in": 899,
  "interval": 5
}

Step 2: Authorize on GitHub

  1. Open the verification_uri in your browser: https://github.com/login/device
  2. Enter the user_code when prompted (e.g., "XXXX-XXXX")
  3. Authorize AgentHub to access your GitHub account

Step 3: Generate API Key

Once authorized on GitHub, generate your API key:

curl -X POST https://prod-agent-hosting-api.useagenthub.com/auth/device/poll \
  -H "Content-Type: application/json" \
  -d '{
    "device_code": "123abc....",
    "name": "My API Key"
  }'

Response:

{
  "api_key": "your-generated-api-key-here"
}

Important: Save this API key securely - it won't be shown again!

Using API Keys

Once you have an API key, include it in the Authorization header with Bearer prefix:

cURL

curl -H "Authorization: Bearer your-api-key-here" \
     https://prod-agent-hosting-api.useagenthub.com/agents

JavaScript/Node.js

const response = await fetch('https://prod-agent-hosting-api.useagenthub.com/agents', {
  headers: {
    'Authorization': 'Bearer your-api-key-here',
    'Content-Type': 'application/json'
  }
});

Python

import requests

headers = {
    'Authorization': 'Bearer your-api-key-here',
    'Content-Type': 'application/json'
}

response = requests.get(
    'https://prod-agent-hosting-api.useagenthub.com/agents',
    headers=headers
)

API Key Security

Best Practices:

  • ✅ Store keys in environment variables, never in code
  • ✅ Use different keys for different environments (dev/staging/prod)
  • ✅ Rotate keys regularly
  • ❌ Never commit keys to version control
  • ❌ Don't share keys in chat/email

Environment Variables:

# .env file
AGENTHUB_API_KEY=your-api-key-here
AGENTHUB_BASE_URL=https://prod-agent-hosting-api.useagenthub.com
// Usage in code
const apiKey = process.env.AGENTHUB_API_KEY;
if (!apiKey) {
  throw new Error('AGENTHUB_API_KEY environment variable is required');
}

Complete Example: CLI Tool

Here's a complete example of implementing device flow authentication in a CLI tool:

import requests
import time

def generate_api_key(key_name="CLI Tool"):
    # Step 1: Initiate device flow
    response = requests.post(
        'https://prod-agent-hosting-api.useagenthub.com/auth/device/initiate',
        headers={'Content-Type': 'application/json'}
    )
    device_data = response.json()
    
    # Step 2: Show user instructions
    print(f"Please visit: {device_data['verification_uri']}")
    print(f"Enter code: {device_data['user_code']}")
    print("Waiting for authorization...")
    
    # Step 3: Poll for API key
    while True:
        token_response = requests.post(
            'https://prod-agent-hosting-api.useagenthub.com/auth/device/poll',
            headers={'Content-Type': 'application/json'},
            json={
                'device_code': device_data['device_code'],
                'name': key_name
            }
        )
        
        if token_response.status_code == 200:
            api_key = token_response.json()['api_key']
            print("✅ API key generated successfully!")
            print("Save this key securely - it won't be shown again:")
            print(f"AGENTHUB_API_KEY={api_key}")
            return api_key
        elif token_response.status_code == 400:
            # Still pending
            time.sleep(device_data['interval'])
            continue
        else:
            print(f"❌ Authentication failed: {token_response.text}")
            return None

def test_api_key(api_key):
    """Test the API key by listing agents"""
    response = requests.get(
        'https://prod-agent-hosting-api.useagenthub.com/agents',
        headers={'Authorization': f'Bearer {api_key}'}
    )
    
    if response.status_code == 200:
        print("✅ API key is working!")
        return True
    else:
        print(f"❌ API key test failed: {response.status_code}")
        return False

# Usage
if __name__ == "__main__":
    api_key = generate_api_key("My CLI Tool")
    if api_key:
        test_api_key(api_key)

Authentication Errors

Common Error Responses

Invalid API Key (401)

{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid or expired"
  }
}

Insufficient Permissions (403)

{
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "This API key does not have permission to access this resource"
  }
}

Rate Limited (429)

{
  "error": {
    "code": "RATE_LIMITED", 
    "message": "Rate limit exceeded. Try again in 60 seconds",
    "retry_after": 60
  }
}

Device Flow Errors

Device code expired:

{
  "error": "expired_token",
  "error_description": "The device code has expired"
}

Authorization pending:

{
  "error": "authorization_pending"
}

Troubleshooting

API Key Not Working:

  1. Ensure you're using the correct API key format
  2. Verify the key was generated successfully
  3. Check you're using the correct base URL: https://prod-agent-hosting-api.useagenthub.com
  4. Test with a simple request like GET /agents

Device Flow Issues:

  1. Make sure you visited the GitHub authorization URL
  2. Enter the exact user code shown (case-sensitive)
  3. Don't poll too frequently - respect the interval from the response
  4. Device codes expire after ~15 minutes - generate a new one if needed

Network Issues:

  1. Verify HTTPS is used (required)
  2. Check for firewall/proxy issues
  3. Ensure your environment can reach prod-agent-hosting-api.useagenthub.com

Security Best Practices

  • Never log API keys - they provide full account access
  • Rotate keys regularly - generate new keys periodically
  • Use environment variables - never hardcode keys in source code
  • Monitor usage - watch for unexpected API calls
  • Secure storage - treat API keys like passwords

Next: Agents API Reference →