如何安全地存储Websocket的唯一客户端ID?

我需要能够知道哪个客户端正在通过Web套接字向服务器发送请求,并将其区别于其他客户端。解决方案是客户端ID,但我不知道存储它的最佳方法,以便客户端可以将其与每个请求一起发送。

客户

var clientId = null;

if (response.method === "connect"){
    clientId = response.clientId
}

评论
发霉的情书
发霉的情书

You could wrap your code with an IIFE which remove the possibility to access variables in the global scope outside of the IIFE. So only the code that runs inside of this IIFE can access the clientId variable. But changing the clientId from, for example, the console wouldn't change a thing.

(function() {
  var clientId = null;

  if (response.method === "connect"){
    clientId = response.clientId
  }
})();

If only overwriting the variable is a problem, then you could alternatively use the Web Storage API to save the id in the browser, either permanently or until the tab has been closed. So you could store it like in the example below.

if (response.method === "connect"){
  sessionStorage.setItem('clientId', JSON.stringify(response.clientId));
}

并在脚本的更下方,甚至在同一页面的另一脚本中使用以下代码,使用clientId:

var storedClientId = sessionStorage.getItem('clientId');
if (storedClientId !== null) { // Check if the id has been set.
  var clientId = JSON.parse(storedClientId);
}

因此,IIFE将无法在自己的范围之外对变量进行修改。 Web Storage API会将您的客户端ID存储在浏览器中,而不是变量中。

点赞
评论