我已经使用 Passport 和express.js 设置了登录/注册界面和机制。我遇到的问题是,用户注册后,我们会被重定向到登录页面,但我们最终可以更改 URL 并立即输入用户个人资料,但这当然不是预期和想要的。我希望用户在注册后未经过身份验证,并且他需要在进入其个人资料之前在登录页面中手动输入他/她的凭据。
router.get('/', isAuthenticated, function(req, res) {
res.render('library', {
// passing the id of and username the connecting user to the dust
userid: req.user._id,
username: req.user.userName
});
});
router.get('/library', isAuthenticated, function(req, res) {
res.render('library', {
// passing the id of and username the connecting user to the dust
userid: req.user._id,
username: req.user.userName
});
});
/* GET login page. */
router.get('/login', function(req, res) {
// Display the Login page with any flash message, if any
res.render('login', {
message: req.flash('message')
});
});
/* Handle Login POST
password.authenticate is used to delegate the authentication
to the login strategy when a HTTP POST is made to /login.
*/
router.post('/login', passport.authenticate('login', {
successRedirect: '/library',
failureRedirect: '/',
failureFlash: true
}));
/* GET Registration Page */
router.get('/signup', function(req, res) {
res.render('signup', {
message: req.flash('message')
});
});
/* Handle Registration POST
password.authenticate is used to delegate the authentication
to the signup strategy when a HTTP POST is made to /signup.
*/
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/login',
failureRedirect: '/signup',
failureFlash: true
}));
并且isAuthenticated
函数/中间件定义如下
var isAuthenticated = function(req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/login');
}
}
我做错了什么?
基本上,注册后,我有一个重定向到 /
的按钮,如果我们被重定向到 library
(就像发生在我身上的情况一样),那么用户应该已经通过身份验证,但我不希望这样......
最佳答案
至少有两种解决方案:
将
session: false
添加到您传递给passport.authenticate('signup', {...})
的配置对象,如 passportjs documentation 中所述。请勿使用 Passport 进行注册。 Passport 的主要用例是用于身份验证(和建立 session ),DIY 注册逻辑或多或少只是从
signup
Passport 中间件复制代码。
关于node.js - 使用 Passport 注册后防止用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34145626/