Passportjs始终无法通过身份验证

时间:2018-01-04 12:06:03

标签: node.js authentication passport.js

我正在尝试将passportjs与以下代码一起使用。

因此,当用户转到http://localhost:3000时,他应该会被自动重定向到/hello,但就像它一样,它会重定向到/hello?failure

我试图调试,环顾四周但没有找到问题和解决方案。

const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');


let app = express();

app.use(session({
    secret: 'mysecret',
    cookie: {
        secure: false
    },
    resave: true,
    saveUninitialized: true
}
));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

passport.use('local-login', new LocalStrategy(function (username, password, done) {

    console.log(username + ' username ');
    console.log(password + ' password ');

    return done(null, { name: 'suhail' });
}));


passport.serializeUser(function (user, done) {
    console.log(user, ' serialize ');
    done(null, user.name);
});

passport.deserializeUser(function (id, done) {
    console.log(id, ' deserialize ');
    done(null, { name: 'suhail' });
});

app.get('/', passport.authenticate('local-login', { successRedirect: '/hello', failureRedirect: '/hello?failure' }));


app.get('/hello', (req, resp, next) => resp.send('hello').end());

app.listen(3000);

我错过了什么?它应该转到http://localhost:3000/hello,因为中间件总是解析。

注意: - 没有调用定义的中间件。当向/hello?failure发出GET请求时,它只会重定向到/

1 个答案:

答案 0 :(得分:1)

您没有在获取请求中提供用户名和密码。因此,永远不会调用Strategycallback。

尝试在路由前添加此中间件,看看我的意思:

app.use((req, res, next) => {
    // fake body content for authentication
    req.body = {username: 'devil', password: '666'}
    next()
})
app.get('/', passport.authenticate('local-login', { successRedirect: '/hello', failureRedirect: '/hello?failure' }));
相关问题