<!-- Source: https://www.wappi.dev/security/api-keys -->

# API Keys

API keys in Wappi provide a secure way to authenticate and authorize access to your API endpoints. They serve as a unique identifier for your application and help protect against unauthorized access.

## Configuration

API keys are configured in your `wappi.json` file and environment variables:

### wappi.json Configuration

```json
{
  "apiKey": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4687121gj2hg3hj12g",
  "private": false,
  "domains": "yourdomain.com, api.yourdomain.com"
}
```

### Environment Variables

```bash
# Current and previous API keys for rotation
AUTH_KEY_CURRENT=your-current-api-key
AUTH_KEY_PREVIOUS=your-previous-api-key

# Environment setting
ENVIRONMENT=prod
```

## How API Keys Work

Wappi uses API keys to:

- Identify and authenticate API requests
- Control access to specific endpoints
- Track usage and implement rate limiting
- Provide audit trails for security monitoring

### Request Authentication

API keys are included in request headers:

```typescript
// Frontend request with API key
fetch('https://api.yourdomain.com/users', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer your-api-key',
    'Content-Type': 'application/json'
  }
})
```

## API Key Generation

When you initialize a new Wappi project, an API key is automatically generated:

```bash
npx wappi init

# During initialization, Wappi generates:
# - A unique API key for your project
# - Configuration files with security settings
# - Environment variable templates
```

### Manual API Key Generation

You can generate new API keys manually for key rotation:

```typescript
// Generate a secure API key
const crypto = require('crypto')
const apiKey = crypto.randomBytes(32).toString('hex')
console.log('New API Key:', apiKey)
```

## API Key Rotation

Wappi supports automatic API key rotation for enhanced security:

### Rotation Configuration

```json
{
  "authRotation": "0 0 * * 0",  // Weekly rotation (every Sunday at midnight)
  "apiKey": "current-key",
  "domains": "yourdomain.com"
}
```

### Rotation Process

1. 1. Generate a new API key
2. 2. Update AUTH_KEY_CURRENT with the new key
3. 3. Move the old key to AUTH_KEY_PREVIOUS
4. 4. Both keys remain valid during transition period
5. 5. Old key expires after the next rotation cycle

## Using API Keys with wappi-fe

Configure API keys in your frontend application:

```typescript
// wappiConfig.ts
import { WappiConfig } from 'wappi-fe/types'

export const WAPPI_CONFIG: WappiConfig = {
  apiUrl: 'https://api.yourdomain.com',
  apiKey: process.env.NEXT_PUBLIC_WAPPI_API_KEY,
  authRedirectPath: '/login'
}
```

### Making Authenticated Requests

```typescript
import { request } from 'wappi-fe'
import { WAPPI_CONFIG } from './wappiConfig'

const response = await request(WAPPI_CONFIG, {
  name: 'Get User Data',
  query: 'User_GetUserData_1_0_0',
  data: { userId: '123' },
  authRequired: true  // Uses API key authentication
})
```

## Endpoint Protection

Protect specific endpoints with API key requirements:

```typescript
// API/User/GetUserData/1.0.0/index.ts
export default async function GetUserData(body: User_GetUserData_1_0_0__Body) {
  // API key validation is handled automatically by Wappi
  // This endpoint is only accessible with valid API key
  
  try {
    const userData = await getUserById(body.userId)
    return {
      success: true,
      data: userData
    }
  } catch (error) {
    throw new Error('Failed to retrieve user data')
  }
}
```

## Security Best Practices

- **Store API keys securely:** Use environment variables, never hardcode in source code
- **Rotate keys regularly:** Implement automatic rotation for enhanced security
- **Use HTTPS only:** Never transmit API keys over unencrypted connections
- **Implement rate limiting:** Prevent abuse and protect against attacks
- **Monitor usage:** Track API key usage for security auditing
- **Restrict domains:** Limit API access to specific domains
- **Log security events:** Monitor failed authentication attempts

## Troubleshooting

### Common Issues

**Invalid API Key Error:**

```json
{
  "success": false,
  "message": "Invalid API key",
  "statusCode": 401
}
```

**Solutions:**

- Verify the API key is correctly set in environment variables
- Check that the key hasn't expired due to rotation
- Ensure the request includes the Authorization header
- Confirm the domain is whitelisted in wappi.json

### Testing API Keys

```typescript
// Test API key validation
curl -X GET https://api.yourdomain.com/health \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json"
```

## AWS Secrets Manager Integration

For production environments, integrate with AWS Secrets Manager for secure key storage:

```typescript
// Store API keys in AWS Secrets Manager
aws secretsmanager create-secret \
  --name "wappi/api-keys" \
  --description "Wappi API Keys" \
  --secret-string '{
    "current": "your-current-api-key",
    "previous": "your-previous-api-key"
  }'
```

```typescript
// Retrieve keys in your application
const AWS = require('aws-sdk')
const secretsManager = new AWS.SecretsManager()

async function getApiKeys() {
  const secret = await secretsManager.getSecretValue({
    SecretId: 'wappi/api-keys'
  }).promise()
  
  return JSON.parse(secret.SecretString)
}
```

URL: https://www.wappi.dev/security/api-keys
