2016-04-30 43 views
2

我是新來的node.js認證。我想使用護照,護照本地,做一些基本的認證。但是當我嘗試它時,它總是會失敗。基本node.js表示認證不起作用

我下面這個教程 http://www.sitepoint.com/local-authentication-using-passport-node-js/

這是我到目前爲止有:

var express = require('express'); 
var app = express(); 
var qs = require('querystring'); 
var pg = require('pg'); 
var passport = require('passport'); 
var LocalStrategy = require('passport-local').Strategy; 
//var expressSession = require('express-session'); 


//app.use(expressSession({secret: 'mySecretKey', cookie: { maxAge: 60000 }, resave: true, saveUninitialized: true})); 
app.use(passport.initialize()); 
app.use(passport.session()); 
app.use(express.static(__dirname + '/public')); 


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

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

// in here I know I am supposed to connect to database, and check if the username,password is there, but for now, i'll just force it to return a user, like they exist. 
passport.use(new LocalStrategy(function(username, password, done) { 
    console.log(1); // does not even print this 
    //return done(null, false); 
    var r = done(null, { 
     'username': username, 
     'password': password 
    }); 
    console.log(r); 
    return r; 
})); 


/* 
* Visit the home page. 
*/ 
app.get('/', function (req, res) { 
    var dest = 'index.html'; 
    res.sendFile(dest, { root: __dirname }); 
}); 
/* 
* Login. 
*/ 
app.post('/login', 
    passport.authenticate('local', { 
     successRedirect: '/loginSuccess.html', 
     failureRedirect: '/loginFailure.html' 
    }) 
); 

var server = app.listen(process.env.PORT || 3000, function() { 
    var host = server.address().address; 
    var port = server.address().port; 

    console.log('My App started at http://%s:%s', host, port); 
}); 

有誰知道這有什麼錯呢?

也任何人都可以解釋這個基本身份驗證是如何工作的,以及serialize/deserialize函數的用途是什麼?

感謝

回答

2

您的應用缺乏body-parser中間件,這是需要解析傳入POST數據。

... 
app.use(bodyParser.urlencoded({ extended : true })); 
app.use(passport.initialize()); 
app.use(passport.session()); 
app.use(express.static(__dirname + '/public')); 
... 
+0

現在它進入成功,但它也記錄到控制檯'body-parser deprecated undefined extended:provide extended option server.js:18:20'。你知道如何解決這個問題嗎? – omega

+0

@omega它的記錄[這裏](https://github.com/expressjs/body-parser#extended):你需要明確地設置'extended'選項。我相應地編輯了我的答案。 – robertklep