Authenticate user for socket.io/nodejs

前端 未结 4 1364
情歌与酒
情歌与酒 2020-12-02 04:34

I have a php login, the user puts in a username/password, it checks the mysql db against the login information. If authenticated a session is created via php and the user ca

4条回答
  •  遥遥无期
    2020-12-02 05:12

    I was looking over the solutions here and decided to give what rcode said a try because it seemed so much easier than the gigantic wall of code accepted answer.

    It ended up working nicely and is quite easy to do.

    I did end up installing a few dependencies which I wanted to avoid but is relatively easy to do with node.

    Type the following in console:

    npm install cookie

    npm install php-unserialize

    This solution uses the session files on the machine - you shouldn't have to change this line.

    session.save_handler = files

    ^ Should be like this in your php.ini file (default).

    (People suggested using memcache, but it seemed like a headache to switch over to that system.)

    Here is the super simple code to retrieve the session data:

    var cookie = require('cookie');
    var fs = require('fs');
    var phpUnserialize = require('php-unserialize');
    
    //This should point to your php session directory.
    //My php.ini says session.save_path = "${US_ROOTF}/tmp"
    var SESS_PATH = "C:/SomeDirectory/WhereYourPHPIs/tmp/";
    
    io.on('connection', function(socket) {
        //I just check if cookies are a string - may be better method
        if(typeof socket.handshake.headers.cookie === "string") {
            var sid = cookie.parse(socket.handshake.headers.cookie);
            if(typeof sid.PHPSESSID === "undefined") {
              console.log("Undefined PHPSESSID");
            }
            else {
                console.log("PHP Session ID: " + sid.PHPSESSID);
                fs.readFile(SESS_PATH + "sess_" + sid.PHPSESSID, 'utf-8', function(err,data) {
                    if(!err) {
                        console.log("Session Data:");
                        var sd = phpUnserialize.unserializeSession(data);
                        console.log(sd);
                    }
                    else {
                       console.log(err);
                    }
                });
            }
        }
    }
    

    Results:

    Edit: I just wanted to add that it may be easier to just have PHP tell your Node.js server when someone logs in and pass the credentials along there.

    I explain how to do this pretty easily in another answer.

    https://stackoverflow.com/a/49864533/1274820

提交回复
热议问题