# Understanding WebSocket Security
## Introduction
WebSockets enable real-time communication but introduce security challenges. This guide covers essential protections.
## The Security Model
WebSockets operate at a different layer than HTTP, requiring different security approaches.
## Authentication
### Token-Based Auth
“`javascript
const ws = new WebSocket(‘wss://api.example.com/ws’, [], {
headers: { ‘Authorization’: `Bearer ${token}` }
});
“`
### Refresh Tokens
Implement token rotation for long-lived connections.
## Authorization
### Channel-Level Permissions
“`javascript
ws.on(‘message’, (data) => {
const message = JSON.parse(data);
if (!userCanAccess(message.channel)) {
ws.send(JSON.stringify({ error: ‘Unauthorized’ }));
ws.close();
}
});
“`
## Input Validation
Always validate and sanitize WebSocket messages:
“`javascript
function validateMessage(data) {
if (typeof data.type !== ‘string’) return false;
if (data.type === ‘chat’ && typeof data.message !== ‘string’) return false;
return true;
}
“`
## Rate Limiting
“`javascript
const messageCounts = new Map();
function rateLimit(ws) {
const count = messageCounts.get(ws) || 0;
if (count > 100) {
ws.close(4001, ‘Rate limit exceeded’);
return false;
}
messageCounts.set(ws, count + 1);
}
“`
## Conclusion
WebSocket security requires attention to authentication, authorization, validation, and rate limiting.
