SocketIO + MySQL的身份验证(SocketIO + MySQL Authenticat

2019-06-24 12:12发布

我想通过以上认证socketIO一个MySQL数据库。 我已经建立了连接,并可以没有问题查询结果,但由于某些原因,我无法通过用户是否被认证为connection socketio的一部分。 这个想法是我的应用程序具有主机和观众。 如果要连接到的应用程序,而不在发送密码QueryString的应用程序假定它是一个浏览器和接受连接。 如果密码被发送,这是对DB检查,接受/拒绝连接。 我想要一个变量传递到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.query使得通过handshakeData访问。 但由于某些原因,它不是通过它通过应用程序。 任何帮助表示赞赏,谢谢。

Answer 1:

你接近,但我建议在设置一个查询字符串PARAM设置请求头。 该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()

需要注意的是,这是不是一个很好的验证结构是很重要的。 直在查询字符串或标题信息传递用户凭证是不安全的。 这种方法让你更接近一个更安全的方法,虽然。 我建议寻找到一个auth库像passport.js或everyauth。 您可以子在此代码,利用这些库存储在运行您检查会话信息。



文章来源: SocketIO + MySQL Authentication