Skip to content

Instantly share code, notes, and snippets.

@t3tra-dev
Last active January 24, 2025 03:45
Show Gist options
  • Save t3tra-dev/a6d285a24bc0da6a30b2b1f5db890c49 to your computer and use it in GitHub Desktop.
Save t3tra-dev/a6d285a24bc0da6a30b2b1f5db890c49 to your computer and use it in GitHub Desktop.
JavaScript(Node.js + Express)でWebSocketの認証方法サンプル

tsのが良かったかもしれん

NYSL(煮るなり焼くなり好きにしろライセンス)

const express = require('express');
const WebSocket = require('ws');
const app = express();
const wss = new WebSocket.Server({ noServer: true });
const server = app.listen(3000);
server.on('upgrade', (request, socket, head) => {
const auth = request.headers.authorization;
if (!auth || !isValidBasicAuth(auth)) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
function isValidBasicAuth(auth) {
const [scheme, credentials] = auth.split(' ');
if (scheme !== 'Basic') return false;
const [username, password] = Buffer.from(credentials, 'base64')
.toString()
.split(':');
return username === 'user' && password === 'password';
}
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });
wss.on('connection', (ws) => {
let isAuthenticated = false;
ws.on('message', (message) => {
if (!isAuthenticated) {
try {
const authMessage = JSON.parse(message);
if (authMessage.type === 'auth' &&
authMessage.username === 'user' &&
authMessage.password === 'password') {
isAuthenticated = true;
ws.send(JSON.stringify({ type: 'auth', status: 'success' }));
} else {
ws.close();
}
} catch (err) {
ws.close();
}
return;
}
// 認証後のメッセージ処理
if (isAuthenticated) {
// 通常のメッセージ処理
}
});
});
const express = require('express');
const jwt = require('jsonwebtoken');
const WebSocket = require('ws');
const url = require('url');
const app = express();
const wss = new WebSocket.Server({ noServer: true });
const JWT_SECRET = 'your-secret-key';
const server = app.listen(3000);
server.on('upgrade', (request, socket, head) => {
const { query } = url.parse(request.url, true);
const token = query.token;
try {
jwt.verify(token, JWT_SECRET);
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} catch (err) {
socket.destroy();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment