简体   繁体   English

无法在Express.js上的Passport.js中访问req.user

[英]Unable to access req.user in Passport.js on Express.js

req.user not accessible anywhere except its origin function. 除了原始功能外, req.user在任何地方都无法访问。

I read that passport attaches the user to every request after authentication. 我读到护照经过身份验证后会将用户附加到每个请求上。

I want to stop any user from accessing the inner pages through the url bar thus skipping the login page or if his session is already active he must be redirected to the user page. 我想阻止任何用户通过URL栏访问内部页面,从而跳过登录页面,或者如果他的会话已经处于活动状态,则必须将其重定向到用户页面。 These two things can be done only if I get access to req.user in all the middlewares. 仅当我在所有中间件中都可以访问req.user ,才能完成这两件事。

app.js link app.js链接

app.js:- app.js: -

app.post('/',passport.authenticate('local',{failureRedirect: '/'}),
function(req,res,next){
console.log(req.user); //req.user defined here only not in users.js
res.redirect('/users');
});

users.js:- users.js: -

router.get('/users', function(req, res, next) {
console.log(req.user);//undefined    
res.render('users');
});

DeserializeUser:- DeserializeUser: -

passport.deserializeUser(function(id, done) {
db.findById(id, function(err, user) {
done(err, user);
console.log(user) //undefined 
});
});

It doesn't look like your app is set up to support sessions, which is generally what's needed for Passport to "remember" that a user has logged in, and to populate req.user . 看来您的应用程序没有设置为支持会话,这通常是Passport“记住”用户已登录并填充req.user

The most common session middleware for Express is express-session , and it relatively easy to set up. Express最常用的会话中间件是express-session ,它相对容易设置。

For a quick check, to see if this is the problem, you can add the following to your app: 为了快速检查问题是否存在,可以将以下内容添加到您的应用中:

app.use(session({ secret: 'super secret' }));

Make sure you add it before app.use(passport.session()) . 确保 app.use(passport.session()) 之前添加它。

If that works, you should read up on how to configure a session store, and what the various other options of the session middleware are. 如果可行,您应该阅读如何配置会话存储以及会话中间件的各种其他选项。

create a middleware function with this : passport.authenticate('local',{failureRedirect: '/'}) as content and use it in every route you wanna authenticate. 创建一个带有以下内容的中间件功能: passport.authenticate('local',{failureRedirect: '/'})作为内容,并在您要验证的每条路径中使用它。 Or use it in app.use(that_function) to authenticate whole app 或者在app.use(that_function)使用它来验证整个应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM