简体   繁体   English

如何在 Socket.IO 客户端中动态设置握手身份验证?

[英]How to dynamically set auth in handshake in Socket.IO client?

On the frontend/client-side, I have an implementation where I secure my socket.io connection using auth token.在前端/客户端,我有一个实现,其中我使用身份验证令牌保护我的 socket.io 连接。 This auth token is updated in the store every few minutes.此身份验证令牌每隔几分钟在商店中更新一次。

const authToken = getToken()
socket = io(WS_BASE_URL, {
    auth: {
        token: authToken
    }
});

In this current implementation, when the socket tries to reconnect , authToken is not updated.在当前的实现中,当套接字尝试重新连接时, authToken不会更新。 How to dynamically set it every time reconnect attempt is made?每次尝试reconnect时如何动态设置它?

socket = io(WS_BASE_URL, {
    auth: {
        token: () => getToken()
    }
});

I want this kind of implementation where I pass a function to get the token every time from the store.我想要这种实现,我每次都通过 function 从商店获取令牌。 Or is there any way we can modify handshake data in the reconnect_attempt event?或者有什么方法可以修改reconnect_attempt事件中的握手数据?

socket.io.on("reconnect_attempt", () => {
    // update handshake
});

socket.io 2.x client api document has this socket.io 2.x客户端api文档有这个

"The query content can also be updated on reconnection:" “查询内容也可以在重新连接时更新:”

socket.on('reconnect_attempt', () => {
  socket.io.opts.query = {
    token: 'fgh'
  }
});

I think you use 4.x because you use auth option, but I think it is basically the same.我认为你使用 4.x 是因为你使用了auth选项,但我认为它基本上是一样的。 The middleware at server side will get the update token when a socket reconnect.服务器端的中间件将在套接字重新连接时获取更新令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM