File size: 6,494 Bytes
eb846d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
---
title: 'Authentication & Security'
description: 'Configure authentication and security settings for MCPHub'
---

## Overview

MCPHub 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
# 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
{
  "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
# 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

MCPHub 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
# 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
{
  "groupId": "dev-team",
  "permissions": {
    "servers": ["read", "write", "execute"],
    "tools": ["read", "execute"],
    "logs": ["read"],
    "config": ["read"]
  }
}
```

## API Authentication

### JWT Token Authentication

```javascript
// 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
# 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
# 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
{
  "cors": {
    "origin": ["https://your-frontend.com"],
    "credentials": true,
    "methods": ["GET", "POST", "PUT", "DELETE"]
  }
}
```

### Rate Limiting

Protect against abuse with rate limiting:

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

## Session Management

### Session Configuration

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

### Logout and Session Cleanup

```javascript
// 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
// 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
# Check user exists and password is correct
curl -X POST http://localhost:3000/api/auth/verify \
  -d '{"username": "user", "password": "pass"}'
```

**Token Expiration**

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

**Permission Denied**

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

### Debug Authentication

Enable authentication debugging:

```bash
DEBUG=mcphub:auth npm start
```

## Integration Examples

### Frontend Integration

```javascript
// 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
// 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' });
  }
};
```