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

# Authentication guide

> Configure authentication and access control for Pcnaid MCP Hub.

## Overview

Pcnaid MCP Hub provides flexible authentication mechanisms to secure your MCP server management platform. The system supports multiple authentication methods and role-based access control.

## Authentication Methods

### Environment-based Authentication

Configure basic authentication using environment variables:

```bash theme={null}
# Basic auth credentials
AUTH_USERNAME=admin
AUTH_PASSWORD=your-secure-password

# JWT settings
JWT_SECRET=your-jwt-secret-key
JWT_EXPIRES_IN=24h
```

### Database Authentication

For production deployments, enable database-backed user management:

```json theme={null}
{
  "auth": {
    "provider": "database",
    "database": {
      "url": "postgresql://user:pass@localhost:5432/mcphub",
      "userTable": "users"
    }
  }
}
```

## User Management

### Creating Users

Create users via the admin interface or API:

```bash theme={null}
# Via API
curl -X POST http://localhost:3000/api/auth/users \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d '{
    "username": "newuser",
    "email": "user@example.com",
    "password": "securepassword",
    "role": "user"
  }'
```

### User Roles

Pcnaid MCP Hub supports role-based access control:

* **Admin**: Full system access, user management, server configuration
* **Manager**: Server management, group management, monitoring
* **User**: Basic server access within assigned groups
* **Viewer**: Read-only access to assigned resources

## Group-based Access Control

### Assigning Users to Groups

```bash theme={null}
# Add user to group
curl -X POST http://localhost:3000/api/groups/{groupId}/users \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"userId": "user123"}'
```

### Group Permissions

Configure group-level permissions:

```json theme={null}
{
  "groupId": "dev-team",
  "permissions": {
    "servers": ["read", "write", "execute"],
    "tools": ["read", "execute"],
    "logs": ["read"],
    "config": ["read"]
  }
}
```

## API Authentication

### JWT Token Authentication

```javascript theme={null}
// Login to get token
const response = await fetch('/api/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    username: 'your-username',
    password: 'your-password',
  }),
});

const { token } = await response.json();

// Use token for authenticated requests
const serversResponse = await fetch('/api/servers', {
  headers: { Authorization: `Bearer ${token}` },
});
```

### API Key Authentication

For service-to-service communication:

```bash theme={null}
# Generate API key
curl -X POST http://localhost:3000/api/auth/api-keys \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d '{
    "name": "my-service",
    "permissions": ["servers:read", "tools:execute"]
  }'

# Use API key
curl -H "X-API-Key: your-api-key" \
  http://localhost:3000/api/servers
```

## Security Configuration

### HTTPS Setup

Configure HTTPS for production:

```yaml theme={null}
# docker-compose.yml
services:
  mcphub:
    environment:
      - HTTPS_ENABLED=true
      - SSL_CERT_PATH=/certs/cert.pem
      - SSL_KEY_PATH=/certs/key.pem
    volumes:
      - ./certs:/certs:ro
```

### CORS Configuration

Configure CORS for web applications:

```json theme={null}
{
  "cors": {
    "origin": ["https://your-frontend.com"],
    "credentials": true,
    "methods": ["GET", "POST", "PUT", "DELETE"]
  }
}
```

### Rate Limiting

Protect against abuse with rate limiting:

```json theme={null}
{
  "rateLimit": {
    "windowMs": 900000,
    "max": 100,
    "message": "Too many requests from this IP"
  }
}
```

## Session Management

### Session Configuration

```json theme={null}
{
  "session": {
    "secret": "your-session-secret",
    "cookie": {
      "secure": true,
      "httpOnly": true,
      "maxAge": 86400000
    },
    "store": "redis",
    "redis": {
      "host": "localhost",
      "port": 6379
    }
  }
}
```

### Logout and Session Cleanup

```javascript theme={null}
// Logout endpoint
app.post('/api/auth/logout', (req, res) => {
  req.session.destroy();
  res.json({ message: 'Logged out successfully' });
});
```

## Security Best Practices

### Password Security

* Use strong password requirements
* Implement password hashing with bcrypt
* Support password reset functionality
* Enable two-factor authentication (2FA)

### Token Security

* Use secure JWT secrets
* Implement token rotation
* Set appropriate expiration times
* Store tokens securely in httpOnly cookies

### Network Security

* Use HTTPS in production
* Implement proper CORS policies
* Enable request validation
* Use security headers (helmet.js)

### Monitoring Security Events

```javascript theme={null}
// Log security events
const auditLog = {
  event: 'login_attempt',
  user: username,
  ip: req.ip,
  userAgent: req.headers['user-agent'],
  success: true,
  timestamp: new Date(),
};
```

## Troubleshooting

### Common Authentication Issues

**Invalid Credentials**

```bash theme={null}
# Check user exists and password is correct
curl -X POST http://localhost:3000/api/auth/verify \
  -d '{"username": "user", "password": "pass"}'
```

**Token Expiration**

```javascript theme={null}
// Handle token refresh
if (response.status === 401) {
  const newToken = await refreshToken();
  // Retry request with new token
}
```

**Permission Denied**

```bash theme={null}
# Check user permissions
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:3000/api/auth/permissions
```

### Debug Authentication

Enable authentication debugging:

```bash theme={null}
DEBUG=mcphub:auth npm start
```

## Integration Examples

### Frontend Integration

```javascript theme={null}
// React authentication hook
const useAuth = () => {
  const [user, setUser] = useState(null);

  const login = async (credentials) => {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials),
    });

    if (response.ok) {
      const userData = await response.json();
      setUser(userData.user);
      return true;
    }
    return false;
  };

  return { user, login };
};
```

### Middleware Integration

```javascript theme={null}
// Express middleware
const authMiddleware = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
};
```
