当前位置: 首页 > 面试题库 >

SocketIO + MySQL认证

阴培
2023-03-14
问题内容

我正在尝试通过socketIO在MySQL
DB上进行身份验证。我已经建立了连接,并且可以毫无问题地查询结果,但是由于某些原因,我无法将用户是否通过connection套接字验证。这个想法是我的应用拥有主持人和查看者。如果在未发送密码的情况下连接到该应用程序,则QueryString该应用程序将视为其查看者并接受连接。如果发送了密码,则会对照数据库进行检查并接受/拒绝连接。我希望将变量传递给,connection以便可以在我的应用程序事件中使用它。这是我到目前为止的内容,但显然data.query['ishost']并没有传递到应用程序中。

sio.configure(function() {
    sio.set('authorization', function (data, accept) {
        UserID = data.query['username'];

        try {
            UserID = UserID.toLowerCase();
        } catch(err) {
            return accept("No WebBot Specified. ("+err+")", false);
        }

        // if not sending a password, skip authorization and connect as a viewer
        if (data.query['password'] === 'undefined')
        {
            return accept(null, true);
        }
        // if sending a password, attempt authorization and connect as a host
        else
        {
            client.query(
            'SELECT * FROM web_users WHERE username = "'+UserID+'" LIMIT 1',
              function selectCb(err, results, fields) {
                if (err) {
                  throw err;
                }
                // Found match, hash password and check against DB
                if (results.length != 0)
                {
                    // Passwords match, authenticate.
                    if (hex_md5(data.query['password']) == results[0]['password'])
                    {
                        data.query['ishost'] = true;
                        accept(null, true);
                    }
                    // Passwords don't match, do not authenticate
                    else
                    {
                        data.query['ishost'] = false;
                        return accept("Invalid Password", false);
                    }
                }
                // No match found, add to DB then authenticate
                else
                {
                    client.query(
                        'INSERT INTO web_users (username, password) VALUES ("'+UserID+'", "'+hex_md5(data.query['password'])+'")', null);

                    data.query['ishost'] = "1";
                    accept(null, true);
                }

                client.end();
              }
            );

            // Should never reach this
            return accept("Hacking Attempt", false);
        }

        // Definitely should never reach this
        return accept("Hacking Attempt", false);
    });
});

写入data.querymake使其可以通过handhakeData访问。但是由于某种原因,它没有通过应用程序传递。任何帮助表示赞赏,谢谢。


问题答案:

您已经结束了,尽管我建议您设置请求标头,而不要设置查询字符串参数。data授权函数中的变量是握手数据,其中包含您可以使用的请求标头和cookie信息。这是设置cookie的示例:

在服务器上

io.configure(function() {
    io.set('authorization', function(handshake, callback) {
        var cookie, token, authPair, parts;

        // check for headers
        if (handshake.headers.cookie && 
            handshake.headers.cookie.split('=')[0]=='myapp') {

            // found request cookie, parse it
            cookie   = handshake.headers.cookie;
            token    = cookie.split(/\s+/).pop() || '';
            authPair = new Buffer(token, 'base64').toString();
            parts    = authPair.split(/:/);

            if (parts.length>=1) {
                // assume username & pass provided, check against db
                // parts[0] is username, parts[1] is password
                // .... {db checks}, then if valid....
                callback(null, true);
            } else if(parts.length==1) {
                // assume only username was provided @ parts[0]
                callback(null,true);
            } else {
                // not what we were expecting
                callback(null, false);
            }
        }
        else {
            // auth failed
            callback(null, false);
        }
    });
});

在客户端上

致电 之前socket.connect,使用您的身份验证/用户信息设置一个cookie:

function writeCookie(value, days) {
    var date, expires;

    // days indicates how long the user's session should last
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = "myapp="+Base64.encode(value)+expires+"; path=/";
};

// for a 'viewer' user:
writeCookie('usernameHere', 1);

// for the 'host' user:
writeCookie('usernameHere:passwordHere', 1);

除非您的浏览器支持,否则您将需要在客户端上使用Base64库btoa()

重要的是要注意,这不是一个好的身份验证结构。直接在查询字符串或标头信息中传递用户凭据并不安全。但是,此方法使您更接近于更安全的方法。我建议您查看一个类似password.js或everyauth的身份验证库。您可以将此代码细分为利用那些库在运行检查时存储的会话信息。



 类似资料:
  • python-socketio 是 Socket.IO 服务器的 Python 实现。 示例代码: import socketioimport eventletimport eventlet.wsgifrom flask import Flask, render_templatesio = socketio.Server()app = Flask(__name__)@app.route('/')d

  • Flask-SocketIO Socket.IO integration for Flask applications. Sponsors The following organizations are funding this project: Socket.IO Add your company here! Many individual sponsors also support this

  • spray-socketio 是 spray 的扩展,实现对 Socket.io 的支持。

  • 这是一个Socket.IO服务器端实现,基于netty框架,适合于 socket.io 0.9-1.0版本(虽然socket.io 目前还处于 0.9版本,会支持到1.0)

  • Netty-socketio 是一个 Java 语言版本的 Socket.IO 服务器的实现,基于 Netty 框架开发。 特性: Supports 0.7...0.9.16 (netty-socketio 1.6.6) and 1.0+ (netty-socketio latest version) version of Socket.IO-client Supports xhr-polling

  • 主要内容:在创建表时设置默认值约束,在修改表时添加默认值约束,删除默认值约束默认值(Default)的完整称呼是“默认值约束(Default Constraint)”,用来指定某列的默认值。在表中插入一条新记录时,如果没有为某个字段赋值,系统就会自动为这个字段插入默认值。 例如,员工信息表中,部门位置在北京的较多,那么部门位置就可以默认为“北京”,系统就会自动为这个字段赋值为“北京”。 默认值约束通常用在已经设置了非空约束的列,这样能够防止数据表在录入数据时出现错误。 在