How to keep the session active when redirecting fr

2019-07-22 13:15发布

问题:

I am working on an Express project(MEAN). i have my login/register page at myDomain.com and on login i want to redirect the user to user.myDomain.com . I am storing the session in MongoDb using session storage module. I can redirect the user to the subdomain but since the session is not maitained in between the domain and subdomain.. it redirects user to the login page. I have looked and tried everything from

Using Express and Node, how to maintain a Session across subdomains/hostheaders https://github.com/jaredhanson/passport/issues/125 Maintaining login session across subdomains in nodejs mongostore

But i am still lost and could not find a proper solution for thise. Can you please help me.

Edit: I did this but id did not help me.

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(cookieParser());
app.use(express.static('../app'));

app.use(session({
  secret:appConfig.SECRET,
  resave:false,
  saveUninitialized:true,
  domain: '.myDomain.com',
  store: sessionstore.createSessionStore({
      type: 'mongodb',
      host: 'localhost',         // optional
      port: 27017,               // optional
      dbName: 'MyDataBase',       // optional
      collectionName: 'sessions',// optional
      timeout: 10000             // optional
      // authSource: 'authedicationDatabase',        // optional
      // username: 'technicalDbUser',                // optional
      // password: 'secret'                          // optional
      // url: 'mongodb://user:pass@host:port/db?opts // optional
  }),
  cookie: {
         path: '/',
         domain: '.myDomain.com',
         maxAge: 1000 * 60 * 24 // 24 hours
     }
}));

回答1:

I had the same problem before. Maybe you could have a try like this:

  app.use(session({
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 30,
    domain:'.dreamon.so' // That's what you need.
  },
  store: new RedisStore({
    host: settings.redis.HOST,
    port: settings.redis.PORT
  }),
  secret: settings.session.SECRET,
  resave: true,
  saveUninitialized: true
}));

But remember to clear browser cookie before you make an other test.