Using Express and Node, how to maintain a Session across subdomains/hostheaders

I have a single node server that responds to requests and redirects a user based on host headers. The usage is that the static/home site lives at www and each user has their own sub domain (i.e. www.example.com and site.example.com). The routing is as per site.js.

When the user is not logged in they are redirected to login.

I am discovering that the session is not maintained when the user is redirected to their sub domain. I guess this is expected, but I am wondering if there is a way to maintain the same session across both sub domains.

I was hoping that if they were logged in and returned to www.example.com they would see a different view that included a link to logout / their dashboard, etc. My workaround at the moment, I'm thinking, is to just create the session on their subdomain and if they do return to www it will just be as if they are not logged in.

Anyone dealt with this before or have answers on how to handle sessions in this manner?

I think the issue may be in users.js where I redirect to 'http://site.example.com' as its not a relative path...

Here is the relevant code (the user lookup is done using MongoDB and I've left it out as its working fine - the line that calls this service is users.authenticate)...

server.js:

app.configure -> app.set "views", "#{__dirname}/views" app.set "view engine", "jade" app.use express.bodyParser() app.use express.methodOverride() app.use express.cookieParser() app.use express.session { key: "KEY", secret: "SECRET", store: new MemoryStore(), cookie: { domain: 'example.com', maxAge : 1000*60*60*24*30*12 } } app.use express.static "#{__dirname}/public" app.use express.logger "short" app.use express.favicon "#{__dirname}/public/img/favicon.ico" app.use app.router

site.js:

module.exports = (app) -> app.get '/', (req, res) -> console.log "/ hit with #{req.url} from #{req.headers.host}" domains = req.headers.host.split "." org = if domains then domains[0] else "www" if org == "www" res.render "index", { layout: null } else if req.session.user console.log "session established" res.render "app", { layout: null } else console.log "no session" res.redirect "http://www.example.com/accounts/login"

users.js:

users = require('../services/users') module.exports = (app) -> app.get "/accounts/login", (req, res) -> res.render "login", { layout: null, locals: { returnUrl: req.query.returnUrl } } app.post "/accounts", (req, res) -> users.authenticate app, req.body.login, req.body.password, (user) -> if user req.session.user = user res.redirect "http://#{user.orgName}.example.com" else res.render "login", { layout: null, locals: { returnUrl: req.body.url } } app.get "/accounts/logout", (req, res) -> console.log "deleting user from session" delete req.session.user res.redirect "http://www.example.com

To test it locally on OSX, I have added www.example.com and site.example.com in to my hosts file so that the DNS lookups get handled locally.

-------------Problems Reply------------

First of all to allow browser to make cross-domain requests you need to set headers on server side. This solution works for normal request as well as AJAX. In your express configure function:

Express 4.0:

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');

var app = express();

app.use(cookieParser());
app.use(session({
secret: 'yoursecret',
cookie: {
path: '/',
domain: 'yourdomain.com',
maxAge: 1000 * 60 * 24 // 24 hours
}
}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});

Access-Control-Allow-Origin can be set to '*' if no cross-domain cookies exchange for sessions needed. To have cookies and session shared cross-domain you need to set specific Access-Control-Allow-Origin to actually domain where request is made from, that's why req.headers.origin - is perfect for that.

Using domain it wont work well on localhost - so make sure you disable it in development environment, and enable on production. It will enable shared cookies across top and sub domains.

This is not all. Browsers it self won't send cookies over cross domain requests, and this have to be forced. In jQuery you can add extra parameter in $.ajax() request:

xhrFields: { withCredentials: true }

For non jQuery, just have XHR constructor and set this parameter:

xhr.withCredentials = true;

And you are ready to do cross-domain with shared session.

Did you make sure you have your cookies set to the top-level domain so it can be read by all subdomains? Then it's just a matter or persisting your session data in memory, a db, whatever as usual. I don't have my dev machine up and running, but it'll be something like this in your app.configure().

app.use(express.cookieParser());

app.use(express.session({
key: 'A_SESSION_KEY',
secret: 'SOMETHING_REALLY_HARD_TO_GUESS',
store: new express.session.MemoryStore,
cookie: {
path : '/',
domain : 'yourdomain.com',
httpOnly : true,
maxAge : 1000*60*60*24*30*12 //one year(ish)
}
}));

Note: If using Express 4 and the new cookie-session module, the code looks like

{
secret: <session_secret> ,
store: <session store> ,
domain: '.domain.com',
}

This bit me, but the API has changed.

Category:session Views:0 Time:2012-01-30

Related post

  • Express.js, Node.js Jade - Following the expressjs.com tutorials, and getting errors 2011-05-01

    Well I'm trying to get into Node.js / Express.js - however I've been having a few issue going through the screencast, the first issue, now resolved, was pretty obvious when it was spotted (Express.js, Node.js Jade vim). However, I'm now getting the f

  • Is there anyway Express in Node.js can have more than one static folder? 2011-08-09

    I'm working on a project where there is a user uploaded collection of styles, scripts and images and then their is my app's collection of styles, scripts and images. They're two different places on my server. Is there anyway I can setup Express in No

  • Learning Express for Node.js 2011-11-15

    Anyone have pointers to good resources for learning Express? I'm aware of the documentation and the nodetuts.com videos. Curious if there are any other good resources out there. --------------Solutions------------- If I would do it all over again wit

  • How do I maintain PHP sessions across multiple domains on the same server? 2008-10-28

    I am looking for a way to maintain PHP sessions across multiple domains on the same server. I am going to be integrating my sites with a Simple Machines Forum so I will need to use MySQL based sessions. Thanks! --------------Solutions------------- De

  • Maintaining the session even after the browser is closed 2010-05-25

    Could anyone tell how to maintain a session (in PHP) so that the session contains are preserved and are accessible even after the browser is restarted. In general a session expires with the closing of a browser, but I want the session NOT TO BE CLOSE

  • Can a browser maintain multiple sessions with one server? 2010-06-11

    Is there a way to maintain multiple sessions with one server within the browser? Here is what I am trying to accomplish: User1 has exclusive access to ContentA and User2 has exclusive access to ContentB. I want to be able to allow User3 to login mult

  • how to maintain the session in the same page 2010-08-10

    in my pageload i have got the session["name"] When i use this code to save: Stream stream = null; request = (HttpWebRequest)WebRequest.Create(url); response = (HttpWebResponse)request.GetResponse(); When it comes to this line: response = (HttpWebResp

  • Maintaining One Session Per Form When Using an Intermediate Service Layer 2010-10-18

    In Building a Desktop To-Do Application with NHibernate, Oren Eini (a.k.a. Ayende Rahien) shares that the general recommended NHibernate practice is to use one session per form in a desktop application. In the example given, this is easily implemente

  • Maintaining a session over multiple pages 2010-10-18

    I am having trouble designing a way to maintain a session with a cookie across multiple pages. I am doing something very similar to this tutorial. I check the password and username from a splash page, and if it is correct then I set a cookie and fill

  • Maintaining a Session throughout the day 2010-10-26

    I need to maintaing the Session throughout the day? On or before session expires, how do I enforce session throughout the day without giving any session timeout either in IIS or web.config? Note: Default Session Timeout in IIS – 20 minutes. Thanks in

  • How can i maintain a session using php PHPSESSID 2010-11-29

    I am using Scriptable web browser (simplebrowser) http://www.lastcraft.com/browser_documentation.php and it does not seem to have a way to: session_start(); set the PHPSESSID value Browse to few pages using simplebrowser session_destroy(); so it migh

  • Maintain http-session via AuthenticationToken and Authenticator 2011-01-27

    I'm writing my own Authenticator and AuthenticationService and want to manage/maintain a http-session, consisting of two cookies and one sessionid, per account in the Authenticator-System of android. So that other apps/activity can reuse the session/

  • Can I use EJB Stateless Bean with CDI to maintain user session? 2011-06-13

    Based on this post http://www.adam-bien.com/roller/abien/entry/ejb_3_1_killed_the I use in my app @Named @Stateless bean for communication with a database (injecting EntityManager here) and display information on a jsf page. It's great facilitation s

  • maintain multiple session request over webservices in java 2011-08-27

    I want to implement following solution (described in a image) using Java Web Services When ever a user request with a valid credentials using web services , a session is created over server and that server (who receives the request ) creates a connec

  • How to maintain login session in Spring 2011-12-19

    I am trying to understand how to login a user and maintain his session using Springs. Is there a website which will give me sample code? --------------Solutions------------- SpringSource has a pet clinic reference app. There is a specific chapter tha

  • Sessions in asp.net? Maintain the session? 2012-02-09

    In web application, i have admin module and it contain login page also, i am maintaining the sessions throught the admin if session is null it is redirecting to login page of admin, but when i write the page name in url [which is a page of admin modu

  • Maintain PHP Session in web app on iPhone 2012-04-03

    I have a jquery mobile web app. On my iPhone when I am on the web app I have a login and session variables. If I leave the app to go to another location on the phone and then return to the web app, I have to log in again. It seems like the session is

  • How To Maintain PHP Session State With Another Application 2012-04-29

    GOAL: Maintain session state between a PHP application and a Coldfusion application which together, comprise the entire application. CURRENT METHOD: Upon logging into our Coldfusion application (the only way to login, i.e., cannot login via the PHP a

  • Security Issues:Maintaining HTTP session only in cookies 2012-04-30

    Can somebody explain me the security issues which might arrise(also how) if I maintain HTTP session only in cookie(s)? --------------Solutions------------- You can code a session management by use of cookies only. It will require many pieces to manag

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.083 (s). 11 q(s)