-
How to implement reliable authorization? For example with passportJS or something like it. |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments 10 replies
-
It's a basic web server. It doesn't support middlewares like Passport.js. But you can implement almost everything on top of it. Read the documentation to understand how things work and go ahead! |
Beta Was this translation helpful? Give feedback.
-
@mrlika |
Beta Was this translation helpful? Give feedback.
-
I don't think that the best practiced are related to this project. They are related to HTTP protocol in general. |
Beta Was this translation helpful? Give feedback.
-
I think that the cookies are the way to go: |
Beta Was this translation helpful? Give feedback.
-
😂😂🤣 |
Beta Was this translation helpful? Give feedback.
-
Use cookie ( const {App} = require('uWebSockets.js')
const cookie = require('cookie')
const app = App()
app
.ws('/*', {
upgrade(res, req, context) {
const _cookie = cookie.parse(req.getHeader('cookie'))
// validate the cookie somehow
// and set _logged true or false
let _logged = true
res.upgrade(
{_logged},
req.getHeader('sec-websocket-key'),
req.getHeader('sec-websocket-protocol'),
req.getHeader('sec-websocket-extensions'),
context
)
},
open(ws) {
// disconnect if not logged
if (!ws._logged) {
ws.end()
console.log('unauthorized', 'https://m.youtube.com/watch?v=OP30okjpCko')
return
}
}
// ...more code
})
.any('/*', (res, req) => {
// set cookie
res.writeHeader('Set-Cookie', '_token=jwt; SameSite=Strict; HttpOnly')
res.end('cookie sample')
})
.listen('::', 3132, token => {
console.info(token)
}) |
Beta Was this translation helpful? Give feedback.
-
@lagden the point of the upgrade handler is to deny the request before the socket opens so you would want to update that Here is JsonWebToken example app.ws('/', {
upgrade:(res, req, context) => {
try { res.user = decodeJwtCookie(res, req, 'cookieName'); }
catch { return res.writeStatus('401').end(); }
res.upgrade({ uid: res.user._id }, req.getHeader('sec-websocket-key'), req.getHeader('sec-websocket-protocol'), req.getHeader('sec-websocket-extensions'), context);
},
open: ws => console.log('open-ws', ws.uid)
});
const getCookie = (res, req, name) => { res.cookies ??= req.getHeader('cookie'); return res.cookies && res.cookies.match(getCookie[name] ??= new RegExp(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`))?.[2]; };
const decodeJwtCookie = (res, req, name) => require('jsonwebtoken').verify(getCookie(res, req, name), env.jwtSecret);
|
Beta Was this translation helpful? Give feedback.
@lagden the point of the upgrade handler is to deny the request before the socket opens so you would want to update that
Here is JsonWebToken example