Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js user authentication using passport

(updated code with serialization functions - still redirects to /failedRedirect)

I'm trying to get simple username/password authentication going using the passport package, but failing. In the example below I've tried to verify that authentication works by basically always returning a valid authentication (regardless of what gets passed), but for some reason it fails and passport redirects to the failed login link.

If anybody could help me out in figuring out how to get this example to simply authenticate anything, I should be able to manage from there.

The code in coffeescript is:

express = require "express"
passport = require "passport"
LocalStrategy = require("passport-local").Strategy

passport.use(new LocalStrategy( (username, password, done) ->
  console.log "LocalStrategy invoked"
  done(null, {id: 1, name: "Marius"})
))

passport.serializeUser (user, done) ->
  done null, user

passport.deserializeUser (obj, done) ->
  done null, obj

app = express.createServer()

app.configure ->
  app.use express.bodyParser()
  app.use express.static("./public")
  app.use express.cookieParser("SOMESECRET")
  app.use express.session
    secret: "SOMESECRET"
    cookie:
      maxAge: 60000
  app.use passport.initialize()
  app.use passport.session()
  app.set "view", "./srv/views"
  app.set "view engine", "jade"

app.get "/login", (req, res) ->
  res.send "login page"

app.post "/login", passport.authenticate("local",
  failureRedirect: "/failedRedirect"
  successRedirect: "/successRedirect"
  failureFlash: true)

app.listen 8082

Solved: Ok, I believe there were a few reasons why I could not get it working. The serialize stuff may be one (I haven't tested), but since Jared said they were needed, I'm leaving them in (he's the author of Passport). The other confusion may be related to express versions and my confusion with npm. I believe I tested both the latest v2 of express, but I've also tested v3, which I am running now. For version three, you probably should check out the connect-flash module on Github as well, as some to the "flash" stuff which is used in Jared's examples was moved out of express v3 (so the module puts it back in...). And finally, make sure you post using the proper named input names (username and password by default).

like image 764
Marius Kjeldahl Avatar asked Jun 10 '12 14:06

Marius Kjeldahl


1 Answers

It looks to me like you're missing the necessary user serialization logic to establish a login session. If I add these two functions to the JavaScript code, it works:

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

You'll want to serialize the users according to your needs. Details are at the bottom of this page: http://passportjs.org/guide/configuration.html

like image 127
Jared Hanson Avatar answered Oct 13 '22 00:10

Jared Hanson