我是javascript和node的新手。我按照护照JS的指南,我收到错误"无法找到本地策略"。我不知道为什么。我的代码,基本上是从网站上获取的。
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, mongoose = require('mongoose')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
app.use(passport.initialize());
//to configure the passport
app.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done){
console.log(username);
console.log(password);
People.findOne({username:username},
function(err, user){
if(err){return done(err); }
if(!user){
return done(null, false, {message:
'Incorrect username'});
}
if(!user.validPassword(password)){
return done(null, false, {message:
'Incorrect Password'});
}
return done(null, user);
});
}
));
//route to authenticate the user
app.post('/login',
passport.authenticate('local', { successRedirect:'/accessed',
failureRedirect: '/access'})
);
我的错误是"未找到本地策略",我查看了local-strategy模块并找到了定义它的函数。所以我假设错误位于我试图访问该变量的方式中。
我的服务器设置为
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
答案 0 :(得分:12)
这是使用本地护照的样板。配置中间件的顺序很重要。它还实现了serializeUser / deserializeUser,它们似乎在您的代码中缺失。
var express = require('express')
, http = require('http')
, path = require('path')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var app = express();
passport.use(new LocalStrategy(function(username, password, done) {
// insert your MongoDB check here. For now, just a simple hardcoded check.
if (username === 'foo' && password === 'bar')
{
done(null, { user: username });
}
else
{
done(null, false);
}
}));
passport.serializeUser(function(user, done) {
// please read the Passport documentation on how to implement this. We're now
// just serializing the entire 'user' object. It would be more sane to serialize
// just the unique user-id, so you can retrieve the user object from the database
// in .deserializeUser().
done(null, user);
});
passport.deserializeUser(function(user, done) {
// Again, read the documentation.
done(null, user);
});
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'secret' }));
app.use(passport.initialize());
app.use(passport.session());
// route to authenticate the user
app.post('/login', passport.authenticate('local', {
successRedirect: '/accessed',
failureRedirect: '/access'
}));
// app.listen(3012);
当您使用curl -v -d "username=foo&password=bar" http://127.0.0.1:3012/login
时,您会看到自己被重定向到/accessed
,这意味着身份验证有效。