Client authentication using websockets and express-session
JamesGDiaz opened this issue · 1 comments
Hi Tamas its me again.
I hope you can help me, Im using you boilerplate and I ditched the socket.io you included in favour of the more streamlined plain websocket ( ws package in npm).
What I'm trying to do is only allow the http connection upgrade to the websocket server on the requested endpoint IF and only if the client is authenticated in the React client you made, I haven't made any changes to that.
I have several routes in my app that point to different endpoints like this. See the second one where verifyClient is specified, but the request sent by the client doesnt seem to provide any kind of cookie or session information, and thus the connection is always rejected.
How can I identify which clients are authenticated, so as not to allow anyone to connect to my endpoints with any websocket client with a simple "ws://mydomain.com/websocket ?
(the session.sessionParser
is exported from src/config/services/session
const wssApp = new SocketServer({
noServer: true
verifyClient: (info, done) => {
session.sessionParser(info.req, {}, () => {
console.log(info.req.session)
done(info.req.session)
})
}
})
/* Websockets functionality */
wssRelay.on('connection', ws => { /* ...work...*/ })
wssApp.on('connection', ws => { /* ... other work...*/ })```
/* And configured the endpoints like this: */
const websocketConfig = server => {
server.on('upgrade', function upgrade (request, socket, head) {
const pathname = new Url(request.url).pathname
if (pathname === '/app') {
websocket.wssApp.handleUpgrade(request, socket, head, function done (ws) {
websocket.wssApp.emit('connection', ws, request)
})
} else if (pathname === '/relay') {
websocket.wssRelay.handleUpgrade(
request,
socket,
head,
function done (ws) {
websocket.wssRelay.emit('connection', ws, request)
}
)
} else {
socket.destroy()
}
})
}
Hi James,
I made the authentication with Passport.js, so you can use the default request.isAuthenticated()
method to check if the user is logged in. For example see the checkLogin function.