问题
My sample application is as follows
var util = require("util")
restify = require("restify"),
q = require("q"),
_ = require("lodash");
//Create Server
var server = restify.createServer({
name: "TestAuth"
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
//Initialize Passport
var passport = require("passport"),
LocalStrategy = require("passport-local").Strategy;
server.use(passport.initialize());
passport.use(new LocalStrategy(
function(username, password, done) {
return done(null, "Test")
}));
//Session setup
server.post("/login", function(req, res, next) {
passport.authenticate("local", function(err, user, info) {
console.log(util.format("%s is logged in!", user))
res.send(200);
return next();
})(req, res, next);
});
server.listen(8080);
When I make the request /login?username=test&password=test it hits the authenticate callback but "user" is false. When I just use
server.post("/login", passport.authenticate("local");
I get a Bad Request response from restify.
回答1:
This passport documentation page shows, in the "Custom Callback" section at the bottom, that, for the way you are using passport in your main snippet, the request method should be a 'get', not a 'post'. I copy here the code snippet from that page:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
That page has other examples of how passport can be used, including the "local" variant that you attempted.
来源:https://stackoverflow.com/questions/22969874/having-issues-with-integrating-passport-local-with-restify