【问题标题】:Connect client socket to a cookie将客户端套接字连接到 cookie
【发布时间】:2021-02-03 03:24:12
【问题描述】:

我正在制作一个聊天程序。

我正在使用 Nginx 服务器和 NodeJS。

我已经通过 ssl 设置了一个 websocket,并且工作正常。

我决定使用 cookie 进行身份验证。

有两个至关重要的功能:

mconnection.prototype.make_server_https=function(){
console.log('Make server https');

var cthis=this;
var server_https=modules.https.createServer({
    key: this.ssl_key,
    cert:this.ssl_cert,
    ca:this.ssl_ca
    },(request,response)=>{
        console.log('### CreateServer ###');

        console.log('CreateServer, Request:');
        console.log(request);

        console.log('CreateServer, Response:');
        console.log(response);

        console.log('######');

mconnection.prototype.make_server_websocket=function(){
var server_websocket=new modules.ws.Server({server:this.server_https});

var cookie = require("cookie");

var cthis=this;
//whenever a new client connects with the server.
server_websocket.on('connection', function(client_socket, request){
    console.log('### On Connection ###');

    console.log('OnConnection, Client Socket:');
    console.log(client_socket);
    console.log('OnConnection, Request:');
    console.log(request);

    console.log('######');

如果我确实在客户端 url 中声明端口号,
函数 make_server_https 会运行并且在其中我可以访问 cookie 并通过响应对象设置它。

但在原始网址中,
函数 make_server_websocket 得到运行,并且我可以访问服务器上的 client_socket。但似乎我可以访问 cookie。

我需要 client_websocket 来启动与这个给定客户端的连接。而且我需要以某种方式将其与 cookie 登录信息联系起来。

但我从来没有同时拥有两者,所以我不知道如何连接它们以进行登录。

我可能误解了一些东西,任何正确方向的帮助将不胜感激。

【问题讨论】:

  • 一旦你设置了cookie,浏览器就会在每个请求中发送cookie。 request 对象应该包含在下一个请求中应该可用的 cookie。
  • 不,当 url 没有端口号时,请求对象中永远不会有 cookie。我在做 httponly。
  • 在连接时我认为我不能设置 cookie,因为我没有响应对象。在 make_server_https 中我无法建立连接,因为我没有 client_socket 对象。它完全不工作。
  • 您的第一个请求是 GET 索引页面,您可以在其中 SET-COOKIE 然后它将在下一个 websocket 请求中可用,因为您需要从节点服务器提供索引页面,如果您决定使用登录系统,然后您可以在成功登录时SET-COOKIE
  • 我不太明白。在 createserver 中,如果 url 中说明了端口号,则调用它,我重定向到原始 url 并设置 cookie。是的。之后,可以通过请求访问 cookie,但只能在 createserver 中访问。在 on 连接中,请求对象仍然没有返回任何 cookie。也不会在未来的请求中。

标签: javascript node.js authentication cookies


【解决方案1】:

您必须使用 GET 从节点服务器为您提供索引页面,然后当请求到达后端时,您将拥有响应对象,如果未从后端设置,则该对象可用于 SET-COOKIE

在GET请求完成后COOKIE将被添加到浏览器中,当下一次请求websocket连接时COOKIE将被浏览器添加到REQUEST HEADERS中的请求中,这将通过请求在后端可用对象。

如果您决定在登录系统中使用它,那么您可以在成功登录时SET-COOKIE

【讨论】:

    【解决方案2】:

    我明白了。它是一个在标题上调用的事件,而不是在连接上。在那里我可以推到标题上。

    【讨论】:

      猜你喜欢
      • 2015-02-08
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 2013-02-14
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多