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

# Authentication

> Secure WebSocket authentication using API keys

# WebSocket Authentication

WebSocket connections require API key authentication for secure access to real-time news streams.

## Authentication Method

WebSocket authentication uses your API key provided during the connection handshake.

### API Key Setup

1. **Get Your API Key**
   * Login to [Byul API Dashboard](https://www.byul.ai/api/dashboard)
   * Your API key is displayed on the dashboard
   * API keys start with `byul_v2_`

2. **Connection Authentication**
   ```javascript theme={null}
   const socket = io('wss://api.byul.ai/news-v2', {
     auth: { apiKey: 'byul_api_key' }
   });
   ```

## Authentication Flow

1. **Connection Request**: Client connects with API key in auth options
2. **Server Validation**: Server validates API key and plan permissions
3. **Authentication Success**: Server emits `auth:success` event with user details
4. **Ready for Subscriptions**: Client can now subscribe to news streams

### Authentication Success Event

```javascript theme={null}
socket.on('auth:success', (data) => {
  console.log('Authentication successful');
  console.log('Plan:', data.user.plan);
  console.log('Email:', data.user.email);
  
  // Now safe to subscribe to news
  socket.emit('news:subscribe', {
    minImportance: 7,
    startDate: '2024-01-01T00:00:00.000Z'
  });
});
```

**Success Response Structure:**

```json theme={null}
{
  "message": "WebSocket authentication successful",
  "user": {
    "email": "user@example.com",
    "plan": "pro"
  }
}
```

## Error Handling

### Authentication Errors

```javascript theme={null}
socket.on('news:error', (error) => {
  console.error('Authentication failed:', error.message);
  
  switch (error.code) {
    case 'INVALID_API_KEY':
      console.log('Please check your API key');
      break;
    case 'PLAN_REQUIRED':
      console.log('WebSocket requires Pro or Enterprise plan');
      break;
    case 'RATE_LIMITED':
      console.log('Too many connection attempts. Please wait.');
      break;
  }
});
```

**Common Error Codes:**

* `INVALID_API_KEY` - API key is invalid or malformed
* `PLAN_REQUIRED` - WebSocket access requires Pro/Enterprise plan
* `RATE_LIMITED` - Too many authentication attempts
* `CONNECTION_LIMIT` - Maximum connections exceeded for plan

## Security Best Practices

### Environment Variables

**Never hardcode API keys in your source code.** Use environment variables:

```javascript theme={null}
// ✅ Good - Use environment variables
const socket = io('wss://api.byul.ai/news-v2', {
  auth: { apiKey: process.env.BYUL_API_KEY }
});

// ❌ Bad - Hardcoded API key
const socket = io('wss://api.byul.ai/news-v2', {
  auth: { apiKey: 'byul_api_key' }
});
```

### Production Configuration

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    // config/websocket.js
    export const websocketConfig = {
      url: process.env.WEBSOCKET_URL || 'wss://api.byul.ai/news-v2',
      auth: { 
        apiKey: process.env.BYUL_API_KEY 
      },
      // Additional security options
      transports: ['websocket'], // Disable polling
      upgrade: false,
      rememberUpgrade: false
    };
    ```
  </Tab>

  <Tab title="React">
    ```jsx theme={null}
    // .env
    REACT_APP_BYUL_API_KEY=byul_api_key

    // src/config/websocket.js
    export const websocketConfig = {
      url: 'wss://api.byul.ai/news-v2',
      auth: { 
        apiKey: process.env.REACT_APP_BYUL_API_KEY 
      }
    };
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import os
    from dotenv import load_dotenv

    load_dotenv()

    # config/settings.py
    WEBSOCKET_CONFIG = {
        'url': 'wss://api.byul.ai/news-v2',
        'auth': {
            'apiKey': os.getenv('BYUL_API_KEY')
        }
    }
    ```
  </Tab>
</Tabs>

### API Key Protection

**Backend Only**: Keep API keys on your backend servers. Never expose them to client-side JavaScript in production.

**Key Rotation**: Regularly rotate your API keys for enhanced security.

**Access Control**: Restrict API key access to authorized team members only.

## Connection Examples

### Basic Authentication

```javascript theme={null}
import { io } from 'socket.io-client';

const socket = io('wss://api.byul.ai/news-v2', {
  auth: { apiKey: process.env.BYUL_API_KEY }
});

socket.on('connect', () => {
  console.log('Connected to WebSocket');
});

socket.on('auth:success', (data) => {
  console.log('Authenticated successfully:', data.user.plan);
});

socket.on('news:error', (error) => {
  console.error('Authentication error:', error.message);
});
```

### With Reconnection

```javascript theme={null}
const socket = io('wss://api.byul.ai/news-v2', {
  auth: { apiKey: process.env.BYUL_API_KEY },
  
  // Reconnection settings
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000
});

socket.on('reconnect', (attemptNumber) => {
  console.log(`Reconnected after ${attemptNumber} attempts`);
});

socket.on('reconnect_error', (error) => {
  console.error('Reconnection failed:', error.message);
});
```

### Python Authentication

```python theme={null}
import asyncio
import socketio
import os

sio = socketio.AsyncClient()

@sio.event
async def connect():
    print('Connected to WebSocket')

@sio.on('auth:success')
async def auth_success(data):
    print(f"Authenticated successfully: {data['user']['plan']}")
    
    # Subscribe to news after authentication
    await sio.emit('news:subscribe', {
        'minImportance': 7,
        'startDate': '2024-01-01T00:00:00.000Z'
    })

@sio.on('news:error')
async def auth_error(error):
    print(f"Authentication error: {error['message']}")

async def main():
    await sio.connect(
        'wss://api.byul.ai/news-v2',
        auth={'apiKey': os.getenv('BYUL_API_KEY')}
    )
    await sio.wait()

asyncio.run(main())
```

## Troubleshooting

### Authentication Issues

**Invalid API Key Format**

```
Error: API key must start with 'byul_v2_'
```

* Verify API key format from dashboard
* Check for extra whitespace or characters

**Plan Requirements**

```
Error: WebSocket streaming requires Pro or Enterprise plan
```

* [Upgrade your plan](https://www.byul.ai/api/pricing)
* Verify plan status in dashboard

**Connection Timeout**

```
Error: Authentication timeout
```

* Check network connectivity
* Verify firewall settings allow WebSocket connections
* Try connecting from a different network

### Testing Authentication

Test your authentication setup with a simple connection:

```javascript theme={null}
const socket = io('wss://api.byul.ai/news-v2', {
  auth: { apiKey: 'byul_api_key' },
  timeout: 10000
});

socket.on('connect', () => {
  console.log('✅ Connection successful');
});

socket.on('auth:success', (data) => {
  console.log('✅ Authentication successful');
  console.log('Plan:', data.user.plan);
  socket.disconnect();
});

socket.on('news:error', (error) => {
  console.log('❌ Authentication failed:', error.message);
  socket.disconnect();
});

socket.on('connect_error', (error) => {
  console.log('❌ Connection failed:', error.message);
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="News Subscription" href="/websocket/news/subscription">
    Subscribe to filtered news streams
  </Card>

  <Card title="Error Handling" href="/websocket/error-handling">
    Handle connection errors and implement retry logic
  </Card>

  <Card title="Connection Management" href="/websocket/connection">
    Advanced connection configuration and monitoring
  </Card>

  <Card title="Examples" href="/websocket/examples/nodejs">
    Production-ready implementation examples
  </Card>
</CardGroup>
