Prevent Expressjs from creating a session when requests contain an authorization header?

前端 未结 4 857
野的像风
野的像风 2021-02-06 04:26

I have an API that can be called either using a browser where requests are transactional and have a session OR directly, eg. using curl, where requests are atomic. Browser reque

4条回答
  •  执笔经年
    2021-02-06 05:09

    An alternative approach to reducing the amount of sessions stored in your session storage is to set a default maxAge to something low. Then, when you actually need sessions stored longer, like after a user logins, you can set req.session.cookie.expires = null;. Also don't forget to set the session expiration to something low when the user logs out.

    Here's an example:

    // set default to something low
    app.use(session({
      resave: true,
      saveUninitialized: true,
      cookie: {
        maxAge: 5 * 60 * 1000 // 5 minutes
      },
      secret: secrets.sessionSecret,
      store: new MongoStore({
        url: yourUrl,
        auto_reconnect: true
      })
    }));
    
    // on successful login, 
    // set expiration to null or something longer than default
    var time = 14 * 24 * 3600000; //2 weeks
    req.session.cookie.maxAge = time;
    req.session.cookie.expires = new Date(Date.now() + time);
    req.session.touch();
    
    // on logout, reset expiration to something low  
    var time = 5 * 60 * 1000; // 5 minutes
    req.session.cookie.maxAge = time; //2 weeks
    req.session.cookie.expires = new Date(Date.now() + time);
    req.session.touch();
    

    This is particularly useful when remote monitoring your app because if the monitoring is frequent enough, the sessions will fill up fast.

提交回复
热议问题