如何使CookieSession仅在某些路径中处于活动状态?

时间:2013-11-19 07:10:40

标签: node.js session express

我希望会话仅对应用程序的某些路径有效。

  1. /cookieFolder/1/cookieFolder/3及其所有子路径都应该有权访问会话。
  2. /cookieFolder/2及其所有子路径不应有权访问会话
  3. 目前我有以下代码:

    app.use(express.cookieParser());
    app.use(express.cookieSession({secret:"HELLO", key:"sc", cookie:{path:"/cookieFolder/1", httpOnly:false}  }));
    app.use(express.cookieSession({secret:"HELLO", key:"sc", cookie:{path:"/cookieFolder/3", httpOnly:false}  }));
    ....
    app.get('/', routes.index);
    app.get('/cookieFolder', routes.index);    
    app.get('/cookieFolder/1', routes.index);     
    app.get('/cookieFolder/2', routes.index);    
    app.get('/cookieFolder/3', routes.index);
    

    routes.index

      if(req.session.count){
        req.session.count = req.session.count + 1;
      }else{
        req.session.count = 1;
      }      
      res.render('index', { title: req.session.count });
    

    点击/cookieFolder/3增量req.session.count。但是多次点击/cookieFolder/1,计数会话变量永远保持在1

1 个答案:

答案 0 :(得分:0)

您必须稍微改变方法。在以下行中,您完全覆盖了选项

app.use(express.cookieSession({secret:"HELLO", key:"sc", cookie:{path:"/cookieFolder/1", httpOnly:false}  }));
app.use(express.cookieSession({secret:"HELLO", key:"sc", cookie:{path:"/cookieFolder/3", httpOnly:false}  }));

在下面的options对象中,“path”键的值告诉ExpressJS将任何会话设置为指定的路径,

{
    secret : "HELLO",
    key : "sc",
    cookie : {
        path : "/cookieFolder/3", //All cookies set in this path only
        httpOnly : false
    }
}

详细说明,由于指定了显式路径,ExpressJS使set-cookie标题如下,

set-cookie: sc=<somesessionid>; path=/cookieFolder/3;...

因此,浏览器仅读取此路径的cookie。换句话说,您只能在地址栏中按住路径“/ cookieFolder / 3”从浏览器中读取任何cookie。

所以我建议你按照要求解决问题,

1.让ExpressJS使用默认路径选项,方法如下,

app.use(express.cookieSession({
    secret : "HELLO",
    key : "sc",
    cookie : {
        // path : "/cookieFolder/1", //Remove this line
        // httpOnly : false //Use it as Optional
    }
}));

2.设置cookie如下所示,通过这样做,我们可以强制浏览器将cookie作为请求标头的一部分发送回来,只有特定的路径。因此,您可以在服务器端检查cookie是否可用。

if(/*<some condition 1>*/){
res.cookie('cookiename1', 'cookieValue1', { path: '/cookieFolder/1' });
}    
if(/*<some condition 2>*/){
res.cookie('cookiename3', 'cookieValue3', { path: '/cookieFolder/3' });
}

3.然后,您可以在上面指定的路由处理程序中访问cookie,如下所示

if(!!req.cookies.cookiename){
request.session.count = request.session.count || 0;
request.session.count++;
}

注意:还有一种方法,只需将路径特定的Cookie设置为res.cookie('cookiename', 'cookieValue', { path: '/cookieFolder/' });,然后您可以稍后在ExpressJS路由器回调中跳过路径'/ cookieFolder / 2'。