Sunday, 4 June 2017

Express, Passportjs persistent login not working

I'm using Express and Passport to sign in but there is a problem: the persistent login session doesn't work.

If I log req.isAuthenticated() It's alway false.

I'm using Custom Callback from Passport and fetch to make the call. The data received from fetch is working: { success: true, user }.

When I'm not using the custom callback (see below) it's working.

Works

app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/login' }));

Not working

app.js

app.use(morgan('tiny'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(express.static(assetPath))
app.use(cookieParser())
app.use(
  session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true },
  })
)
app.use(passport.initialize())
app.use(passport.session())

routes.js

router.post('/login', (req, res, next) => {
  passport.authenticate('local', ({ user, err, message }) => {
    if (err) {
      return res.send({ user, err, message })
    }

    if (!user) {
      return res.send({ user, err, message })
    }

    req.login(user, function(err) {
      if (err) {
        return next(err)
      }
      return res.send({ success: true, user })
    })
  })(req, res, next)
})



via jonathandion

No comments:

Post a Comment