简体   繁体   English

如何在 ReactJS 中以安全的方式跨页面刷新建立持久的 Web 套接字连接?

[英]How to make persistent web socket connection across page refresh in a secure way in ReactJS?

I am using web socket for communicating with back end server from a reactjs client.我正在使用 Web 套接字从 reactjs 客户端与后端服务器进行通信。 Socket is getting closed when a user refreshes the page.当用户刷新页面时,套接字正在关闭。 That is happening as expected.这正如预期的那样发生。 However, my requirement is to have persistent web socket connection across page refresh.但是,我的要求是跨页面刷新具有持久的 Web 套接字连接。 I am currently using localstorage to store access, refresh tokens.我目前正在使用 localstorage 来存储访问、刷新令牌。

I understand this is not a secure way to resolve the problem.我知道这不是解决问题的安全方法。 I want to know if there is any secure way available to achieve my goal.我想知道是否有任何安全的方法可以实现我的目标。

I am not sure if this works because it would be kind of a security breach to be able to let the user connected even though he is not on your page.我不确定这是否有效,因为即使用户不在您的页面上,也可以让用户连接,这将是一种安全漏洞。 (Because as you are refreshing, you leave the page and re-enter it). (因为在刷新时,您离开页面并重新进入)。

Your best bet maybe something with a service worker that can run in the background :)您最好的选择可能是可以在后台运行的服务工作者:)

Since you are using Web Sockets it would be a good idea to use a SharedWorker to create a new thread for your Web Sockets.由于您使用的是 Web 套接字,因此最好使用 SharedWorker 为您的 Web 套接字创建一个新线程。 The difference between a normal WebWorker and a SharedWorker is that the web worker will create a new session in each tab or browser when loading the page, whereas the shared worker will use the same session in each tab.普通 WebWorker 和 SharedWorker 之间的区别在于,Web Worker 会在加载页面时在每个选项卡或浏览器中创建一个新会话,而共享 Worker 将在每个选项卡中使用相同的会话。 So all of your tabs or windows will have the same worker and same Web Socket connection to work with.因此,您的所有选项卡或窗口都将使用相同的工作程序和相同的 Web 套接字连接。

I quoted from this answer which will probably point you to the right direction: https://stackoverflow.com/a/61866896/11665341我引用了这个答案,它可能会指向正确的方向: https : //stackoverflow.com/a/61866896/11665341

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

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