You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已认证用户req.user为undefined问题排查求助

Troubleshooting req.user Being Undefined After Authentication

Hey there, let's walk through why your req.user is coming up undefined even after successful authentication, and why your /user route is returning {}. I've reviewed your code and here are the key issues to fix:

1. Missing Authentication Middleware on Your Route

The biggest red flag is your /user route doesn’t use any Passport authentication middleware. Without this, Passport never runs its logic to attach the authenticated user to req.user.

Fix: Add the appropriate Passport middleware to your route. Since you’re using JWT for auth, update your route code like this:

// routes/user
router.get('/user', passport.authenticate('jwt', { session: false }), (req, res, next) => { 
  res.status(200).send({auth: req.user}); 
});

If you relied on session-based auth previously, use passport.authenticate('session') instead.

2. Mismatched Field in JWT Strategy

In your Passport JWT configuration, you’re querying for a user by username using jwt_payload._id:

models.User.findOne({ where: { username: jwt_payload._id, }, })

This is almost certainly incorrect. When generating JWTs, you likely set _id to the user’s database ID (not their username). Fix the query to target the id field instead:

// Use findByPk for direct ID lookups (cleaner and faster)
models.User.findByPk(jwt_payload._id)
// Or if you need findOne for other conditions:
models.User.findOne({ where: { id: jwt_payload._id, }, })

If you intentionally stored the username in jwt_payload._id, double-check your JWT generation code to confirm this is working as intended.

3. CORS Credentials Disabled

Your CORS middleware has credentials: false, which blocks cookies (including session cookies or JWT-related cookies) from being sent across domains. If your frontend is hosted on a different origin than your backend, this will prevent Passport from receiving the authentication token entirely.

Fix: Update your CORS config to enable credentials:

app.use(cors({ 
  origin: process.env.ALLOW_ORIGIN, 
  credentials: true, // Change this to true
  allowedHeaders: 'X-Requested-With, Content-Type, Authorization, origin, X-Custom-Header', 
  methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS', 
}))

Don’t forget to enable credentials on your frontend requests too (e.g., fetch(url, { credentials: 'include' }) for vanilla JS, or axios.defaults.withCredentials = true for Axios).

4. Deprecated Sequelize find Method

Your deserializeUser uses models.User.find(), which is deprecated in newer Sequelize versions. This could cause the user lookup to fail silently, leading to req.user being undefined.

Fix: Replace find with findByPk (ideal for ID-based lookups) or findOne:

passport.deserializeUser(function(userId, done){
  models.User.findByPk(userId)
    .then(function(user){
      done(null, user);
    }).catch(function(err){
      done(err, null);
    });
});

Quick Debugging Tips

To narrow down issues further, add console logs in key spots:

  • In deserializeUser, log userId and the returned user to confirm the database lookup works.
  • In your JWT strategy, log jwt_payload to verify it contains the correct user identifier.
  • In your /user route, log req.user right before sending the response to check if it’s populated after adding the authentication middleware.

内容的提问来源于Stack Exchange,提问作者randal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:56:04