jaredhanson/passport-local

Session Cookie Not Set?

ronag opened this issue · 3 comments

ronag commented

I'm a bit confused as to how to use this:

Given that:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(expressSession({
  secret: 'MY_SECRET',
  resave: false,
  saveUninitialized: false,
  name: 'sid'
}))
app.use(passport.initialize())
app.use(passport.session())
app.post('/api/login',
  passport.authenticate('local'),
  // Doesn't set the session cookie (`sid`) in res?
  (req, res, next) => res.sendStatus(200)
)
app.get('/user/:id', (req, res, next) => {
  // req does not include `sid` cookie and can thus not be authenticated...? req.user == null
 ...
})
ronag commented

My workaround for now is:

app.post('/api/login',
  passport.authenticate('local'),
  // Doesn't set the session cookie (`sid`) in res?
  (req, res, next) => res.send('s:' + sign(req.sessionID, 'MY_SECRET'))
)

and then have the client manually set the cookie.

th-m commented

If you are confused about the sign method in @ronag example. I found it in the code of express-sessions git repo

var signature = require('cookie-signature')

use like signature.sign(val, secret);

improving more secure:
set cookie server side

app.post('/api/login',
  passport.authenticate('local'),
  // Doesn't set the session cookie (`sid`) in res?
  (req, res, next) => res.cookie('connect.sid', 's:' + signature.sign(req.sessionID, 'MY_SECRET'));
)

but to make it work you should make http call with credentials: true, for exemple with axios something like this

axios
        .post(
          `blabla/api/login`,
          {
            username: 'someValue',
            password: 'someValue'
          },
          {
            withCredentials: true
          }
        )