gpt4 book ai didi

node.js - 没有 Mongoose 的 Passport.js 本地策略

转载 作者:搜寻专家 更新时间:2023-10-31 23:51:42 25 4
gpt4 key购买 nike

我正在尝试查找有关 Node 应用程序最简单的使用 Passport 登录的资源。我的意思是,使用:

中间件:

    app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

app.use(express.static('public'));

Passport :

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

passport.deserializeUser(function(id, done) {
done({ id: id, nickname: "test"})
});


passport.use(new LocalStrategy(
function(username, password, done) {
console.log("test");
if (username === 'username') {
return done(null, { name: "test", id: '1234'});
} else {
return done(null, false, { message: 'Incorrect cred.' });
}
})
)

和重定向:

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

我的应用结构:

/app.js
/public/index.html
/public/login.html

就是这样。 Web 上到处都是带有插件的 Mongoose 的相同示例,每个人都只是简单地相互复制粘贴。

关键是我想稍后在 LocalStrategy 代码中插入我自己的代码(可能会使用 LDAP)。

目前,我没有使用在公共(public)文件夹中创建的页面重定向到/index.html,而是在 index.html 上收到 [object Object]

最佳答案

您的 passport.deserializeUser() 不正确:

passport.deserializeUser(function(id, done) {
done({ id: id, nickname: "test"})
});

它将“用户”对象作为第一个参数传递给 done,这是为错误保留的。这会导致 Express 呈现错误页面,并在其中尝试将错误字符串化,从而导致 [object Object]

试试这个:

passport.deserializeUser(function(id, done) {
done(null, { id: id, nickname: "test"})
});

关于node.js - 没有 Mongoose 的 Passport.js 本地策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43539258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com