WebSockets & Real-Time Communication

How should WebSocket authentication be implemented securely?
class AuthenticatedWebSocket {
    constructor(url, authToken) {
        this.url = url;
        this.authToken = authToken;
        this.connect();
    }

    connect() {
        // Add auth token to URL or headers
        const wsUrl = `${this.url}?token=${this.authToken}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.onopen = () => {
            // Verify authentication success
            this.sendAuthVerification();
        };

        this.ws.onmessage = (event) => {
            if (event.data === 'auth_failed') {
                this.handleAuthFailure();
            }
        };
    }

    sendAuthVerification() {
        this.ws.send(JSON.stringify({
            type: 'auth',
            token: this.authToken
        }));
    }
}
Next Question (13/17)