1

Since PHP sessions are basically cookies, and I am using them to authenticate logged in users (I know, I should move to tokens), is it possible to read the session cookie on my node app? (I want to create a simple chat that gets the logged in username from the PHP session, and on the way allow only logged in users to use the chat)

What would then be the preferred way to do that? (In terms of security as well)

**Edit: I am trying to get something sort of the node equivalent of this in PHP:

if(!isset($_SESSION['user_id']){
   //don't allow access to the chat page
} else {
   //show chat for logged user
}
6
  • 1
    the cookie does not belong to a specific language Commented May 20, 2018 at 22:32
  • thanks, I edited the original post, I am then looking for the node equivalent, of how to show page or not if a specific session is set, or not(from PHP) Commented May 20, 2018 at 22:36
  • 1
    dupe? :stackoverflow.com/questions/3393854/… i dont use node so i cant answer that part of the question Commented May 20, 2018 at 22:38
  • 1
    cookie and sessions are 2 different things, if you are asking about sharing a session data between node and PHP, it is possible but difficult for native sessions, but you might do that with custom sessions offered by different MVC frameworks like symfony, etc... so their entirely depends on your implementation Commented May 20, 2018 at 23:01
  • Furqan thanks. Btw, smith linked to a way of getting the session if you want to take a look. Now assuming I do have the session of the logged in user, what would be the equivalent of displaying content, or not? Commented May 20, 2018 at 23:10

2 Answers 2

2

A cookie is not language specific so if the cookie is there, you could certainly read it with node.js.

BUT, the browser only sends cookies to the server that they are associated with. So, if your PHP server is not part of the same sub-domain as the node.js server and the cookies are configured to allow sharing with sub-domains, then the browser won't send the PHP cookie to your node.js server.

To read cookies with Express, you can use the cookie-parser module. Samples for how to use it are in the doc. After installing the cookie-parser middleware, you would end up referencing:

req.cookie

to access that same cookie. To manage sessions using Express and node.js and keep track of server-side session state, one would typically use the express-session module.

Sign up to request clarification or add additional context in comments.

8 Comments

for testing on localhost, but on a different port, that should work right? it's considered the same domain
@TTnote - Cookies are host-specific, not port specific so a cookie from a server on one port will be sent with a request to a different server on the same host, but different port.
Thank you, but I edited my original post, because my initial intention was quite different than what it seems to be - I actually wanted to know how in node js, after you get the cookie, you either allow to show the page, or not, as you'd easily do in PHP with isset. I really want a concrete example with node, because I can't make it work
@TTnote - What's in the actual cookie that you're looking for? I don't know PHP to know what it's doing, but if you show me the actual cookie string from the http header, I can handle the node.js access to it.
Is it the one you're looking for? I wasn't sure: [PHPSESSID] => fseh3456bv355oqddmtpf158
|
0

If you truly want to access the session data from everywhere as well as other request data using node through globals you might want to consider spawning a worker process for each request and declaring those as globals.

However that is not the "node way"(tm) of doing things, as the http server itself is part of your program and not a web server that is spawning a process to run your script (except for ReactPHP which behaves like nodejs).

Every connection handler gets the request and the output response as parameters, thus they are not accessible unless you forward them to your function calls.

const PORT = 80;

async function connectionHandler(req, res) {
    /* here you implement routing
     * depending on req.url, req.method, req.headers, etc...
     */
}

http.createServer(connectionHandler).listen(PORT);

Here what you might need is an object (associative array) with session_id as key and an object as value. And if the user doesn't have a session_id yet you create it:

const _SESSION = {};

function sessionStart(headers) {
    let id = headers.cookies?.piles_awesome_session_id ?? null;
    if (!id) {
        id = generateSessionId();
        _SESSION[id] = {};
    }
    return id;
}

function generateSessionId() {
    const chars = [[49,57],[97,102]].map(([start, end]) => Array(end-start+1).fill(null).map((n,i) => String.fromCharCode(n+i))).flat();
    return Array(32).fill(null).map(c => chars[Math.floor(Math.random()*chars.length)]).join('');
}

You'd call that by passing req.headers to it inside the connection handler or any route handler if you're using express or a custom router.

function connectionHandler(req, res) {
    const sessionId = sessionStart(req.headers);
    const session = _SESSION[sessionId];
    // don't forget to set the cookie
    // "piles_awesome_session_id"
}

Ideally you'd use a database for storing your session across multiple server instances instead of a variable in memory. Just remember server vars are not request scoped, they will leak between different users, that's why request and response are not globals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.