2017-03-10 59 views
0

以下程序使用passportjs進行用戶名/密碼驗證。我不會犯我犯的錯誤,但我總是重定向到失敗頁面,即返回到登錄頁面。驗證失敗,護照中間件不會被調用

var passport = require('passport') 
    , LocalStrategy = require('passport-local').Strategy 
    , express = require('express'); 


var app = express(); 

app.listen(3000); 

app.use(express.static(__dirname+'/public')); 
app.use(passport.initialize()); 
app.use(passport.session()); 

passport.use(new LocalStrategy(
    function(username, password, done) { 
    console.log(username + ':username'); 
    console.log(password + ':password'); 
    return done(null, [{username:'foo'}]); 
    } 
)); 

app.get('/login',(req,resp) => { 
    var options = { 
     root: __dirname + '/public/' 
    }; 

    resp.sendFile('login.html',options); 
}); 

app.post('/login', 
    passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'}) 
); 

我想了解的passportjs的工作,我看到中間件passport.use(new LocalStrategy(永遠不會被調用。我不知道原因,但可能是失敗的根源。

回答

0

也許護照需要會話嘗試在護照配置前添加app.use(express.session({ secret: 'keyboard cat' }));

您必須命名你的戰略和序列化用戶

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

passport.use('local', new LocalStrategy(
    function(username, password, done) { 
    console.log(username + ':username'); 
    console.log(password + ':password'); 
    return done(null, [{username:'foo'}]); 
    } 
)); 

你的名字在這個如local

app.post('/login', 
    passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'}) 
); 
+0

仍然沒有進入中間件。 –

0

所以我失蹤了由passportjs要求body parser模塊來解析POST請求調用此戰略。這裏是完整的代碼:

var passport = require('passport') 
    , LocalStrategy = require('passport-local').Strategy 
    , express = require('express') 
    , bodyParser = require('body-parser'); 


var app = express(); 

app.listen(3000); 

app.use(express.static(__dirname+'/public')); 
app.use(bodyParser.urlencoded({ extended: false }));// parse application/x-www-form-urlencoded 
app.use(bodyParser.json()); // parse application/json 
app.use(passport.initialize()); 
app.use(passport.session()); 

passport.use('local',new LocalStrategy(
    function(username, password, done) { 
    console.log(username + ':username'); 
    console.log(password + ':password'); 
    return done(null, {username:username}); 
    } 
)); 

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

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


app.get('/login',(req,resp) => { 
    var options = { 
     root: __dirname + '/public/' 
    }; 

    resp.sendFile('login.html',options); 
}); 

app.post('/login', 
    passport.authenticate('local', { successRedirect: '/',failureRedirect: '/login'}) 
);