crossws
crossws copied to clipboard
Implement a method to abort `upgrade` (auth)
Describe the feature
Here you also need to add an authentication check during the upgrade handshake, for example, only authorized users can enter the socket in order to then save the client user information Examle event:
const onAuth = defineEventHandler(event => {
// valid token or more check
event.context.user = {} // save user
})
export default defineWebSocketHandler({
upgrade(req) {
return false // failed connect example JWT.verify(req.headers['Token'])
return {headers:{}} success connect
}
// or new method auth (before the upgrade event)
auth(event) {
const {token} = getQuery(event)
if (!token) {
throw createError('Not authorized')
}
return true // or {headers: {}}
}
})
This is just an example since in this code there is no way to refuse clients who have passed
// Upgrade
async upgrade(req) {
const [res1, res2] = await Promise.all([
opts.hooks?.upgrade?.(req),
await resolveHook(req, "upgrade").then((h) => h?.(req)),
]);
const headers = new Headers(res1?.headers);
if (res2?.headers) {
for (const [key, value] of new Headers(res2?.headers)) {
headers.append(key, value);
}
}
return { headers };
},
Additional information
- [ ] Would you be willing to help implement this feature?