简体   繁体   English

req.user 在 Express 和 Passport 中以未定义的形式返回?

[英]req.user is coming back as undefined with Express and Passport?

When my app redirects to "/" req.user is undefined, but in the twitter callback, req.user gives me the data that I'm looking for.当我的应用重定向到“/”时,req.user 未定义,但在 twitter 回调中,req.user 为我提供了我正在寻找的数据。 I lose the data on redirect.我丢失了重定向数据。 There is still information in req for "/" but not req.user which I need. req 中仍有“/”的信息,但没有我需要的 req.user。

Can anyone help me solve this problem?谁能帮我解决这个问题?

This is my index.js这是我的 index.js

const express = require('express')
const app = express()
const cookieSession = require('cookie-session')
const passport = require('passport');
require('./passport')
const isLoggedIn = require('./Middleware/auth')

app.use(cookieSession({
  name: 'twitter-auth-session',
  keys: ['key1', 'key2']
}))
app.use(passport.initialize());
app.use(passport.session());

app.get('/auth/error', (req, res) => res.send('Unknown Error'))


//, isLoggedIn,

app.get('/', (req,res)=>{
  console.log('HELLOOOOO', req.user)
  res.send(`Hello`)
});

app.get('/logout', (req, res) => {
  req.session = null;
  req.logout();
  res.redirect('/');
})

app.get('/auth/twitter',passport.authenticate('twitter'));
app.get('/auth/twitter/callback',passport.authenticate('twitter', { failureRedirect: '/auth/error' }),
function(req, res) {
  // console.log("REQUEST", req.user)
  res.redirect('/');
});

app.listen(8000,()=>{
  console.log('Server is up and running at the port 8000')
})

This is my passport.js middleware:这是我的 passport.js 中间件:

const passport = require('passport');
const TwitterStrategy = require('passport-twitter').Strategy;

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

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

passport.use(new TwitterStrategy({
  consumerKey: "xxxxxxxxxxx",
  consumerSecret: "xxxxxxxxxxx",
  callbackURL: "http://www.localhost:8000/auth/twitter/callback",
}, function(accessToken, refreshToken, profile, cb) {
  return cb(null, profile);
}));

Ok so after some trial and much error the problem seemed to be with the way that I was using sessions or the cookie-session library.好的,所以经过一些试验和很多错误后,问题似乎与我使用会话或 cookie-session 库的方式有关。

I added the library我添加了库

const session = require('express-session')

I changed我变了

app.use(cookieSession({
  name: 'twitter-auth-session',
  keys: ['key1', 'key2']
}))

to

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

And that seems to have fixed things, just in case you all are looking at this really obscure answer haha.这似乎已经解决了问题,以防万一你们都在看这个非常晦涩的答案哈哈。

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

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