简体   繁体   中英

Using passport.js with yeoman and grunt for authentication

I'm trying to work out how to use passport.js with grunt/yeoman. I have the following:

// at the top of my gruntfile.js
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;

passport.use(new BasicStrategy(
  function(username, password, done) {
    return done(null, true); // I would expect this to always succeed, but still challenge for credentials
  }
));

// further down in my connect config.
livereload: {
    options: {
        middleware: function (connect) {
            return [
                lrSnippet,
                passport.initialize(),
                passport.authenticate('basic', { session: false }),
                mountFolder(connect, '.tmp'),
                mountFolder(connect, yeomanConfig.app)
            ];
        }
    }
}

On every request the response just contains unauthorized . Removing the call to passport.authenticate makes the page work, but obviously there's now no authentication. I've tried changing the order of the middleware and that hasn't helped, and I'm nowhere near an expert with yeoman/grunt so I'm not entirely sure what else to try...

Any help would be greatly appreciated.

I'm thinking that you need to pass an object to done() inside of your BasicStrategy callback. As I recall, passport JS uses this object to populate req.user in express apps, and because of this I would think it probably expects an object not a boolean .

Here is a more robust example of that same function that I use in many apps:

  passport.use(new BasicStrategy(
    function(clientID, clientSecret, done) {
      AuthClient.findOne({ clientID: clientID }, function(err, client) {
        if (err) { return done(err); }
        if (!client) { return done(null, false); }
        if (client.secret != clientSecret) { return done(null, false); }
        return done(null, client);
      });
    }
  ));

As you can see the BasicStrategy is uses to analyze aa clientID and clientSecret which is the equivalent to your username / password combination. Since you aren't actually pulling it from a db as is shown in my example, I would expect if you just follow the suggestion above and pass {} to done(null, {}) , it might work better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM