# Authentication

Learn how to authenticate with the AIDP Platform API.

## Overview

AIDP uses JWT (JSON Web Tokens) for authentication. All API requests require a valid API key or JWT token.

### Authentication Flow

![JWT Authentication Flow](https://2687700396-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FF8uzz8ItUjkBw81bmpg0%2Fuploads%2Fgit-blob-cc57c75c5346fa013f5f5b568df7ee06d5d93d29%2Fjwt-auth.svg?alt=media)

## Getting an API Key

### 1. Sign Up

Create an account at [platform.aidp.dev](https://platform.aidp.dev)

### 2. Generate API Key

1. Navigate to **Settings** → **API Keys**
2. Click **Create New API Key**
3. Give it a descriptive name (e.g., "Production API")
4. Copy the key immediately (it won't be shown again)
5. Store securely (never commit to version control)

### 3. Use API Key

Include in the `Authorization` header:

```bash
curl -H "Authorization: Bearer sk_live_abc123..." \
  https://api.aidp.dev/v1/businesses/search
```

## API Key Types

### Test Keys

For development and testing:

```
sk_test_abc123...
```

**Characteristics**:

* Access to sandbox environment
* No real charges
* Rate limited (100 req/hour)
* Test data only

### Live Keys

For production use:

```
sk_live_abc123...
```

**Characteristics**:

* Access to production environment
* Real charges apply
* Higher rate limits
* Real data

## Authentication Methods

### 1. API Key (Recommended)

Simple and secure for server-to-server communication.

**TypeScript**:

```typescript
import { AIDPClient } from '@aidp/sdk';

const client = new AIDPClient({
  apiKey: process.env.AIDP_API_KEY,
});
```

**Python**:

```python
from aidp import AIDPClient

client = AIDPClient(api_key=os.environ['AIDP_API_KEY'])
```

**cURL**:

```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
  https://api.aidp.dev/v1/businesses/search
```

### 2. JWT Tokens

For user-specific authentication (web/mobile apps).

**Login**:

```http
POST /auth/login
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "secure_password"
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 3600
  }
}
```

**Use Token**:

```bash
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
  https://api.aidp.dev/v1/business/profile
```

### 3. OAuth 2.0

For third-party integrations.

**Authorization URL**:

```
https://platform.aidp.dev/oauth/authorize?
  client_id=YOUR_CLIENT_ID&
  redirect_uri=https://yourapp.com/callback&
  response_type=code&
  scope=read:businesses write:bookings
```

**Exchange Code for Token**:

```http
POST /oauth/token
Content-Type: application/json

{
  "grant_type": "authorization_code",
  "code": "AUTH_CODE",
  "client_id": "YOUR_CLIENT_ID",
  "client_secret": "YOUR_CLIENT_SECRET",
  "redirect_uri": "https://yourapp.com/callback"
}
```

## Token Refresh

Access tokens expire after 1 hour. Use refresh tokens to get new ones:

```http
POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "eyJhbGciOiJIUzI1NiIs..."
}
```

**Response**:

```json
{
  "success": true,
  "data": {
    "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    "expiresIn": 3600
  }
}
```

## Scopes

Control access with OAuth scopes:

| Scope              | Description            |
| ------------------ | ---------------------- |
| `read:businesses`  | Read business profiles |
| `write:businesses` | Create/update profiles |
| `read:bookings`    | View bookings          |
| `write:bookings`   | Create/manage bookings |
| `read:analytics`   | Access analytics data  |
| `read:reviews`     | View reviews           |
| `write:reviews`    | Submit reviews         |

**Example**:

```
scope=read:businesses write:bookings read:analytics
```

## Security Best Practices

### Storing API Keys

✅ **Do**:

* Use environment variables
* Use secret management services (AWS Secrets Manager, HashiCorp Vault)
* Rotate keys regularly
* Use different keys for dev/staging/prod

❌ **Don't**:

* Commit keys to version control
* Hardcode in source code
* Share keys via email/chat
* Use same key across environments

**Example (.env)**:

```bash
# .env (add to .gitignore)
AIDP_API_KEY=sk_live_abc123...
```

**Example (code)**:

```typescript
// ✅ Good
const apiKey = process.env.AIDP_API_KEY;

// ❌ Bad
const apiKey = 'sk_live_abc123...';
```

### Key Rotation

Rotate API keys regularly:

1. Generate new key
2. Update applications with new key
3. Test thoroughly
4. Revoke old key

### Monitoring

Monitor API key usage:

* Track requests per key
* Set up alerts for unusual activity
* Review access logs regularly

## Error Handling

### 401 Unauthorized

```json
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

**Causes**:

* Missing Authorization header
* Invalid API key
* Expired token
* Revoked key

**Solution**:

* Check API key is correct
* Ensure header is included
* Refresh expired tokens
* Generate new key if revoked

### 403 Forbidden

```json
{
  "success": false,
  "error": {
    "code": "FORBIDDEN",
    "message": "Insufficient permissions"
  }
}
```

**Causes**:

* Missing required scope
* Account suspended
* Resource access denied

**Solution**:

* Check OAuth scopes
* Verify account status
* Ensure proper permissions

## Rate Limiting

API keys have rate limits based on plan:

| Plan         | Rate Limit      |
| ------------ | --------------- |
| Free         | 100 req/hour    |
| Professional | 1,000 req/hour  |
| Enterprise   | 10,000 req/hour |

**Headers**:

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1638360000
```

[Learn more about rate limiting →](https://amistan.gitbook.io/aidp-docs/for-developers/rate-limiting)

## Examples

### TypeScript/JavaScript

```typescript
import { AIDPClient } from '@aidp/sdk';

// Using API key
const client = new AIDPClient({
  apiKey: process.env.AIDP_API_KEY,
  environment: 'production',
});

// Using JWT token
const client = new AIDPClient({
  accessToken: userToken,
  onTokenExpired: async () => {
    // Refresh token
    const newToken = await refreshToken(refreshToken);
    return newToken;
  },
});
```

### Python

```python
from aidp import AIDPClient
import os

# Using API key
client = AIDPClient(
    api_key=os.environ['AIDP_API_KEY'],
    environment='production'
)

# Using JWT token
client = AIDPClient(
    access_token=user_token,
    on_token_expired=lambda: refresh_token(refresh_token)
)
```

### cURL

```bash
# Using API key
curl -H "Authorization: Bearer $AIDP_API_KEY" \
  https://api.aidp.dev/v1/businesses/search

# Using JWT token
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
  https://api.aidp.dev/v1/business/profile
```

## Testing

### Sandbox Environment

Test authentication without affecting production:

```
Sandbox API: https://sandbox-api.aidp.dev/v1
Test API Key: sk_test_abc123...
```

### Postman Collection

Import our Postman collection for easy testing:

```bash
# Download collection
curl -O https://api.aidp.dev/postman/collection.json

# Import into Postman
# Set environment variable: AIDP_API_KEY
```

## Support

Need help with authentication?

* 📚 **Documentation**: [API Reference](https://amistan.gitbook.io/aidp-docs/for-developers/api-reference)
* 💬 **GitHub Discussions**: [github.com/aidp/platform/discussions](https://github.com/aidp/platform/discussions)
* 📧 **Email**: <api@aidp.dev>
* 🐛 **Issues**: [GitHub Issues](https://github.com/aidp-platform/issues)

## Next Steps

* [API Reference](https://amistan.gitbook.io/aidp-docs/for-developers/api-reference)
* [Rate Limiting](https://amistan.gitbook.io/aidp-docs/for-developers/rate-limiting)
* [Error Handling](https://amistan.gitbook.io/aidp-docs/for-developers/error-handling)
* [Code Examples](https://amistan.gitbook.io/aidp-docs/for-developers/examples)
