套接字建立后进行socket.io 身份验证

发布于 2024-12-24 23:02:59 字数 559 浏览 0 评论 0原文

我正在开发一款小型多人游戏。我想介绍一下身份验证。我正在使用 Node.js 和 Socket.io。

当用户到达主页时 - 我希望他们加入游戏,无论他们是否登录 - 但他们将无法在其中执行任何操作(只能观看)。

那么我该如何在已经打开的套接字上对用户进行身份验证呢?

如果他们离开网站并返回,我还能保持身份验证吗?你能通过网络套接字传递cookie吗?

编辑

进一步提出我的问题。我可能的想法之一是提供 websocket 连接,然后当他们尝试登录时,它将用户名和密码作为消息传递给 websocket。

client.on('onLogin', loginfunction);

然后,我可以获取用户名和密码,检查数据库,然后获取套接字的会话 ID,并将其传递到某个地方,以表明会话已通过该用户的身份验证。

这安全吗?我仍然可以在套接字上实现 cookie 以便它们可以回来吗? socket.io 中是否有任何方法可以声明套接字现在已经过身份验证,而不是手动检查收到的每条消息?

干杯

I'm working on a small multiplayer game. I'd like to introduce authentication. I'm using Node.js and Socket.io.

When the user arrives that the main page - I want them to join the game whether they are logged in or not - but they will be unable to do anything within it (only watch).

How could I then go about authenticating the user on the already open socket?

Could I maintain the authentication still if they left the site and came back? Can you pass a cookie through a web socket?

EDIT

To further my question. One of the possible thoughts I've had is to provide the websocket connection, then when they try to login in, it passes username and password as a message to the websocket.

client.on('onLogin', loginfunction);

I could then take the username and password, check against the database, then take the session ID of the socket and pass it somewhere to say that session is authenticated to that user.

Is this secure? Could I still implement a cookie on the socket so they could come back? Is there any way within socket.io of stating that the socket is now authenticated instead of manually checking on each message received?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦在深巷 2024-12-31 23:02:59

这实际上并不太难,但你的方法是错误的。有几件事:

  1. 你不能使用socket.io设置 cookie;但是,您可以随时获取任何已连接客户端的 cookie 值。为了设置 cookie,您必须发送一个新的 http 响应,这意味着用户必须首先发送一个新的 http 请求(又名刷新或转到新页面,这听起来对您来说不可能)。< /p>

  2. 是的:socket.io 是安全的(在任何传输的数据都可以的范围内)。

因此,您可以执行以下操作:

在用户的初始连接上,创建具有唯一会话 ID 的 cookie,例如从 Express 的会话中间件生成的 cookie。您需要将它们配置为不在会话结束时过期(否则一旦关闭浏览器就会过期)。

接下来,您应该创建一个对象来存储 cookie 会话 ID。每次设置新的 connect.sid cookie 时,将默认值 false 存储在新对象中(这意味着用户已通过会话进行身份验证,但未通过登录进行身份验证)

在用户登录时,向服务器发送套接字发送,然后您可以在其中验证登录凭据,并随后更新您创建的会话 ID 对象以读取当前套接字 ID 的 true(已登录)。

现在,当收到新的 http 请求时,读取 cookie.sid,并检查它在对象中的值是否为 true。

它应该类似于以下内容:

var express = require('express'),
http = require('http'),
cookie = require('cookie');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);


app.use(express.cookieParser());
app.use(express.session({ 
    secret: 'secret_pw',
    store: sessionStore,
    cookie: { 
        secure: true,
        expires: new Date(Date.now() + 60 * 1000), //setting cookie to not expire on session end
        maxAge: 60 * 1000,
        key: 'connect.sid'
    }
}));

var sessionobj = {}; //This is important; it will contain your connect.sid IDs.

//io.set('authorization'...etc. here to authorize socket connection and ensure legitimacy


app.get("/*", function(req, res, next){
    if(sessionobj[req.cookies['connect.sid']]){
        if(sessionobj[req.cookies['connect.sid']].login == true){
            //Authenticated AND Logged in
        }
        else{
            //authenticated but not logged in
        }
    }
    else{
        //not authenticated
    }

});


io.sockets.on('connection', function(socket){
    sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].login = false;
    sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].socketid = socket.id;

    socket.on('login', function(data){
        //DB Call, where you authenticate login
        //on callback (if login is successful):
        sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid']] = true;
    });

    socket.on('disconnect', function(data){
        //any cleanup actions you may want
    });

});

This isn't actually too hard, but you're approaching it the wrong way. A couple things:

  1. You cannot set a cookie with socket.io; you can, however, get the cookie values of any connected client at any time. In order to set a cookie, you will have to send a new http response, meaning the user must first send a new http request (aka refresh or go to a new page, which it sounds is not a possibility for you here).

  2. Yes: socket.io is secure (to the extent that any transmitted data can be).

As such, you can do the following:

On the user's initial connection, create a cookie with a unique session ID, such as those generated from Express's session middleware. You will need to configure these not to expire on session end though (otherwise it will expire as soon as they close their browser).

Next you should create an object to store the cookie session IDs. Each time a new connect.sid cookie is set, store in your new object with a default value of false (meaning that the user has been authenticated by session, but not by logon)

On the user's login, send a socket emit to the server, where you can then authenticate the login credentials, and subsequently update the session id object you created to read true (logged in) for the current socket id.

Now, when receiving a new http request, read the cookie.sid, and check if its value in your object is true.

It should look something like the following:

var express = require('express'),
http = require('http'),
cookie = require('cookie');

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);


app.use(express.cookieParser());
app.use(express.session({ 
    secret: 'secret_pw',
    store: sessionStore,
    cookie: { 
        secure: true,
        expires: new Date(Date.now() + 60 * 1000), //setting cookie to not expire on session end
        maxAge: 60 * 1000,
        key: 'connect.sid'
    }
}));

var sessionobj = {}; //This is important; it will contain your connect.sid IDs.

//io.set('authorization'...etc. here to authorize socket connection and ensure legitimacy


app.get("/*", function(req, res, next){
    if(sessionobj[req.cookies['connect.sid']]){
        if(sessionobj[req.cookies['connect.sid']].login == true){
            //Authenticated AND Logged in
        }
        else{
            //authenticated but not logged in
        }
    }
    else{
        //not authenticated
    }

});


io.sockets.on('connection', function(socket){
    sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].login = false;
    sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid'].socketid = socket.id;

    socket.on('login', function(data){
        //DB Call, where you authenticate login
        //on callback (if login is successful):
        sessionobj[cookie.parse(socket.handshake.headers.cookie)['connect.sid']] = true;
    });

    socket.on('disconnect', function(data){
        //any cleanup actions you may want
    });

});
夜还是长夜 2024-12-31 23:02:59

Chris,我无法回答,因为我不是 socket.io 方面的专家,但我也许可以尝试为您指出另一个可以帮助您的方向 - 并节省一些开发时间。

但首先,有一个免责声明:我为 Realtime.co 工作,并不想做任何类型的广告。我与开发人员密切合作,我只是想通过为您的问题提供开箱即用的解决方案来帮助您。另外,作为一名游戏玩家,我不能不努力帮助人们推出他们的游戏!

Realtime 使用身份验证/授权层,您可以在其中向用户提供对通道的读/写权限。当用户进入网站时,您可以授予他们对游戏频道的只读权限,一旦他们登录,您就可以授予他们写入权限。这可以通过进行身份验证并重新连接到服务器来轻松完成(这一切都可以在客户端完成)。不过,为了提高安全性,我会在服务器端进行。

Realtime 具有 Node.js API,因此您可以轻松地将其与服务器集成。由于它还具有适用于许多其他平台(包括移动平台)的 API,并且它们的工作方式都相同,因此您实际上可以让您的游戏在同一通信层上的多个平台上运行,同时完全控制通道。

感谢您的阅读。

编辑:

您可以在此处阅读文档以获取更多信息:http://docs.xrtml.org/

Chris, I'm won't be able to answer since I'm not an expert on socket.io, but I can maybe try to point you in another direction that can help you - and take away some development time.

But first, a disclaimer: I work for Realtime.co and am not trying to do any sort of advertising. I work closely with developers and I'm just trying to help you by providing you an out-of-the-box solution for your problem. Also, being a gamer, I can't stay away from trying to help people getting their games out there!

Realtime uses an authentication/authorization layer in which you can provide user read/write permissions to channels. When users enters the website you can give them read only permissions to the game channel and once they login, you can then give them write permissions. This can be easily done by doing an authentication post and reconnecting to the server (it can all be done client side). I would do it server-side, though, to increase security.

Realtime has a Node.js API so you can easily integrate it with your server. Since it also has APIs for many other platforms (including mobile) and they all work the same way, you can actually have your game working in multiple platforms over the same communication layer, while having full control over channels.

Thanks for reading.

Edit:

You can read the documentation here for more info: http://docs.xrtml.org/

无言温柔 2024-12-31 23:02:59

Socket.io 可以选择传递 extraHeaders。人们可以使用它来传递来自客户端的令牌。服务器将使用所需的身份验证算法来解密令牌并获取user_id

socket.js

import io from 'socket.io-client';

export const socket = io('https://remote-url');

export const socketAuth = () => {
  socket.io.disconnect();  //This uses the same socket and disconnect with the server. 
  socket.io.opts.extraHeaders = {
    'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
  };
  socket.io.opts.transportOptions = {
    polling: {
      extraHeaders: {
        'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
      },
    },
  };  
  socket.io.open(); //Opens up a new connection with `x-auth-token` in headers

};

客户端.js

  import { socket, socketAuth } from 'utils/socket';
  socket.on('unauthenticated-messages', () => {
    someAction();
  });

  //After user logs in successfully
  socketAuth();

  socket.on('authenticated-messages', () => {
    someAction();
  });

Socket.io has an option to pass extraHeaders. One can use that to pass a token from the client. The server would use the desired authentication algorithm to decrypt the token and get the user_id.

socket.js

import io from 'socket.io-client';

export const socket = io('https://remote-url');

export const socketAuth = () => {
  socket.io.disconnect();  //This uses the same socket and disconnect with the server. 
  socket.io.opts.extraHeaders = {
    'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
  };
  socket.io.opts.transportOptions = {
    polling: {
      extraHeaders: {
        'x-auth-token': JSON.parse(window.localStorage.getItem('auth-token')),
      },
    },
  };  
  socket.io.open(); //Opens up a new connection with `x-auth-token` in headers

};

client.js

  import { socket, socketAuth } from 'utils/socket';
  socket.on('unauthenticated-messages', () => {
    someAction();
  });

  //After user logs in successfully
  socketAuth();

  socket.on('authenticated-messages', () => {
    someAction();
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文