Last active
August 30, 2024 00:40
-
-
Save naoki-sawada/2f4e135feb3c6bad7f555f59dfb40020 to your computer and use it in GitHub Desktop.
Simple socket.io room and auth example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const io = require('socket.io-client'); | |
const socket = io('http://localhost:3000', { | |
transportOptions: { | |
polling: { | |
extraHeaders: { | |
'Authorization': 'Bearer abc', | |
}, | |
}, | |
}, | |
}); | |
socket.on('connect', () => { | |
console.log('connected!'); | |
socket.emit('room', 'room1'); | |
}); | |
socket.on('message', data => { | |
console.log(data); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const server = require('http').createServer(); | |
const io = require('socket.io')(server); | |
const isValidJwt = (header) => { | |
const token = header.split(' ')[1]; | |
if (token === 'abc') { | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
// io.of('/test'); | |
io.use((socket, next) => { | |
const header = socket.handshake.headers['authorization']; | |
console.log(header); | |
if (isValidJwt(header)) { | |
return next(); | |
} | |
return next(new Error('authentication error')); | |
}); | |
io.on('connection', (socket) => { | |
socket.on('room', room => { | |
console.log(room); | |
socket.join(room); | |
}); | |
}); | |
setInterval(() => { | |
io.sockets.to('room1').emit('message', 'what is going on, party people?'); | |
}, 3000); | |
setInterval(() => { | |
io.sockets.to('room2').emit('message', 'anyone in this room yet?'); | |
}, 3000); | |
server.listen(3000); |
<3 thx
Thank you! It is very helpful.
Thank you, perfect.
Handle Auth for a namespace and go further with connection
Client
(https://cdn.socket.io/4.3.2/socket.io.min.js)
const socket = io.connect(
`${domain}/api/v1/xxx/42`,
{
auth: {
"authorization": `303338ce-d71e-4304-abd2-3cfc40a1589a303338ce-d71e-4304-abd2-3cfc40a1589a`,
},
transports: ['websocket', 'polling'],
}
)
socket.on("connect", () => {
console.log('conected:', socket.id)
})
Server
this._authMiddleware.action here is a custom async express middleware you probably are using in other part of your project
this._io
.of(/^\/api\/v1\/xxx\/(?<id>\d+)$/)
.use((socket: Socket, next) => {
const reqStub = {headers: socket.handshake.auth, user: null}
this._authMiddleware.action(reqStub, {}, (e: any) => {
if (e) {
next(e)
return
}
(socket.request as unknown as {user: string}).user = reqStub.user!
next()
}).catch(e => {
next(e)
})
})
.on('connection', (socket: Socket) => {
socket.emit('msg', `Hello ${(socket.request as unknown as {user: string}).user}`)
})
console.log('shark eats seafood');
console.log('Thank you fery mut');
Fantastic, short, clean and simple. More importat: works
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, exactly what I needed!