Node + Express + Passport: req。用户定义

时间:2023-01-19 23:59:50

My question is similar to this one, but there was no insight into his solution.

我的问题和这个问题很相似,但是对他的解决方案没有深入的了解。

I'm using Passport to auth using Instagram. After successful auth, users are directed to "/". At this point, the request has the user object (aka it's working). However, once I redirect, the req.user is undefined. :'(

我用护照在Instagram上发照片。auth成功后,用户被定向到“/”。此时,请求具有user对象(即它正在工作)。然而,一旦我重定向,req。用户定义。:'(

The odd part is that passport.deserializeUser is being called with each request. It's successfully getting the user object, but somewhere along the middleware road, req.user is not being set (or being unset).

奇怪的是,每个请求都会调用passport.deserializeUser。它正在成功地获取用户对象,但是在中间件道路上的某个地方,req。用户未被设置(或未设置)。

// on successful auth, goto "/" 
app.get('/', function(req, res) {
    // if the request has the user object, go to the user page
    if (req.user) {
        res.redirect("/user/" + req.user._id);
    }

    res.render("index");
}

app.get('/user/:uid', function(req, res) {
    console.log(req.user) // undefined
}

15 个解决方案

#1


30  

Have you set up session state for your app? You need something like this...

你为你的应用设置了会话状态吗?你需要这样的东西……

app.use(session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());

#2


35  

My issue was not specifying to send cookies when using fetch on the client-side. It worked after including the credentials: 'include' field in the request.

我的问题是在客户端上使用fetch时没有指定发送cookie。它在将凭证“include”字段包含到请求之后工作。

fetch('/api/foo', {credentials: 'include'})

#3


11  

I am super new to Node but it was a middleware issue for me. Added bodyParser and rearranged to fix.

我是Node的新手,但这对我来说是一个中间件问题。添加了bodyParser并重新安排修复。

Broken code:

破碎的代码:

app.use(express.cookieParser('secret'));
app.use(express.cookieSession());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'))); 

Working Code:

工作代码:

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

Hope this helps

希望这有助于

#4


7  

Previously I have these code (did not work):

之前我有这些代码(不工作):

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'abcdefg',
    resave: true,
    saveUninitialized: false,
    cookie: { secure: true } // this line
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));

Then I remove the cookie option from session initializer:

然后我从会话初始化器中删除cookie选项:

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'abcdefg',
    resave: true,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));

and now it works.

现在它的工作原理。

#5


3  

In routes, try adding: {session: true}

在路由中,尝试添加:{session: true}

app.get('/auto-login', passport.authenticate('cross', {session: true}))

#6


3  

Yeah enable sessions like @Martin says. But if you are using Express 4.* version, middleware like sessions are not bundled so you need to install it individually.

是的,就像@Martin说的那样。但是如果你用的是特快4。*版本,不捆绑像会话这样的中间件,所以您需要单独安装它。

  1. Add "express-session": "1.4.0" in your package.json
  2. 在包中添加“express-session”:“1.4.0”
  3. npm install
  4. npm安装
  5. use it
  6. 使用它

;

;

var express = require('express');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var app = express()
app.use(cookieParser()) // required before session.
app.use(session({secret: 'keyboard cat'}))

For more information check the express session documentation.

有关更多信息,请参阅快速会话文档。

#7


3  

I encounter the same problem because of just copy & paste following code from express-session documentation, but not fully read the documentation.

我遇到了同样的问题,因为只是复制和粘贴来自express-session文档的代码,而不是完全阅读文档。

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}))

In the documentation, it mentioned:

在文件中,它提到:

However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.

但是,它需要一个支持http的网站,即。, HTTPS对于安全cookie是必要的。如果安全设置,并且您通过HTTP访问您的站点,那么将不会设置cookie。

so if you just have a HTTP connection, remove the secure option,and below code should work:

因此,如果您只有一个HTTP连接,请删除安全选项,下面的代码应该可以工作:

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  //cookie: { secure: true } remove this line for HTTP connection
}))

#8


2  

I had this exact same problem using express 4 and after trying pretty much everything I could find online I finally managed to get it working by adding 'cookie-session'.

我在使用express 4时遇到了同样的问题,在尝试了几乎所有能在网上找到的东西后,我终于通过添加“cookie-session”来让它工作。

var cookieSession = require('cookie-session');

app.use(cookieSession({
  keys: ['key1', 'key2']
}));

#9


1  

When u use http request on client side, remember to attach credentials. In Angular2 you need to add option argument: { withCredentials: true }. After this you will have the same req.sessionID until you reset it again.

当您在客户端使用http请求时,请记住附加凭据。在Angular2中,您需要添加选项参数:{withCredentials: true}。之后你会得到同样的回复。sessionID直到您再次重置它。

this._http.get("endpoint/something", { withCredentials: true })

#10


0  

If your middleware stack is unclear, assuming you have session middleware somewhere, you can save the session before the redirect:

如果您的中间件堆栈不清楚,假设您在某处有会话中间件,您可以在重定向之前保存会话:

if (req.user) {
    req.session.save(function (err) {
        if (err) {
            // ... panic!
        }
        res.redirect("/user/" + req.user._id);
    });
    return;
}

#11


0  

Have you tried to insert in the cookieParser your secretKey?

您是否尝试过在cookieParser中插入您的分泌键?

var passport = require('passport');
var expressSession = require('express-session');

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('mySecretKey'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressSession({
secret: 'mySecretKey',
  resave: false,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

#12


0  

Mine was about cookies & cors. I solved by adding following code to my server:

我的是饼干公司。我通过向我的服务器添加以下代码来解决:

allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); // your website
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' === req.method) {
    res.send(200);
} else {
    next();
}};

#13


0  

Had exactly the same problem. For me, the solution was to use "client-sessions" instead of 'express-session". Probably bad sessions configuration?

也有同样的问题。对我来说,解决方案是使用“客户端会话”而不是“表达会话”。可能坏会话配置?

Not working code:

不是工作代码:

var session = require('express-session');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(session({
    secret: 'random string',
    resave: true,
    saveUninitialized: true,
    cookie: { secure: true }
}));

Working code:

工作代码:

var session = require('client-sessions');

        app.use(bodyParser.urlencoded({ extended: false }));
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(cookieParser());
        app.use(bodyParser.json());
        app.use(session({
        cookieName: 'session',
        secret: 'random string',
        duration: 30 * 60 * 1000,
        activeDuration: 5 * 60 * 1000,
    }));

#14


0  

Once you have your express session setup make sure you have passport serialize & deserialize, in the deserialize function that's when req.user gets generated. See explanation here from another * question.

一旦您有了快速会话设置,请确保您在req的反序列化函数中有passport序列化和反序列化。用户生成。这里是另一个*问题的解释。

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


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

#15


-1  

I had a different issue, something with bcrpt-node and arrow functions.

我有一个不同的问题,关于bcrpt-node和arrow函数。

Code that works:

代码:

userSchema.methods.generateHash = function (password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); 
};

userSchema.methods.isValidPassword = function (password) {
  return bcrypt.compareSync(password, this.password);
};

Code that does not work:

不工作的代码:

userSchema.methods.generateHash = (password) => {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.isValidPassword = (password) => {
  return bcrypt.compareSync(password, this.password);
};

#1


30  

Have you set up session state for your app? You need something like this...

你为你的应用设置了会话状态吗?你需要这样的东西……

app.use(session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());

#2


35  

My issue was not specifying to send cookies when using fetch on the client-side. It worked after including the credentials: 'include' field in the request.

我的问题是在客户端上使用fetch时没有指定发送cookie。它在将凭证“include”字段包含到请求之后工作。

fetch('/api/foo', {credentials: 'include'})

#3


11  

I am super new to Node but it was a middleware issue for me. Added bodyParser and rearranged to fix.

我是Node的新手,但这对我来说是一个中间件问题。添加了bodyParser并重新安排修复。

Broken code:

破碎的代码:

app.use(express.cookieParser('secret'));
app.use(express.cookieSession());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'))); 

Working Code:

工作代码:

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: 'anything' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

Hope this helps

希望这有助于

#4


7  

Previously I have these code (did not work):

之前我有这些代码(不工作):

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'abcdefg',
    resave: true,
    saveUninitialized: false,
    cookie: { secure: true } // this line
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));

Then I remove the cookie option from session initializer:

然后我从会话初始化器中删除cookie选项:

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('abcdefg'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'abcdefg',
    resave: true,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));

and now it works.

现在它的工作原理。

#5


3  

In routes, try adding: {session: true}

在路由中,尝试添加:{session: true}

app.get('/auto-login', passport.authenticate('cross', {session: true}))

#6


3  

Yeah enable sessions like @Martin says. But if you are using Express 4.* version, middleware like sessions are not bundled so you need to install it individually.

是的,就像@Martin说的那样。但是如果你用的是特快4。*版本,不捆绑像会话这样的中间件,所以您需要单独安装它。

  1. Add "express-session": "1.4.0" in your package.json
  2. 在包中添加“express-session”:“1.4.0”
  3. npm install
  4. npm安装
  5. use it
  6. 使用它

;

;

var express = require('express');
var cookieParser = require('cookie-parser')
var session = require('express-session')
var app = express()
app.use(cookieParser()) // required before session.
app.use(session({secret: 'keyboard cat'}))

For more information check the express session documentation.

有关更多信息,请参阅快速会话文档。

#7


3  

I encounter the same problem because of just copy & paste following code from express-session documentation, but not fully read the documentation.

我遇到了同样的问题,因为只是复制和粘贴来自express-session文档的代码,而不是完全阅读文档。

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}))

In the documentation, it mentioned:

在文件中,它提到:

However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.

但是,它需要一个支持http的网站,即。, HTTPS对于安全cookie是必要的。如果安全设置,并且您通过HTTP访问您的站点,那么将不会设置cookie。

so if you just have a HTTP connection, remove the secure option,and below code should work:

因此,如果您只有一个HTTP连接,请删除安全选项,下面的代码应该可以工作:

app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  //cookie: { secure: true } remove this line for HTTP connection
}))

#8


2  

I had this exact same problem using express 4 and after trying pretty much everything I could find online I finally managed to get it working by adding 'cookie-session'.

我在使用express 4时遇到了同样的问题,在尝试了几乎所有能在网上找到的东西后,我终于通过添加“cookie-session”来让它工作。

var cookieSession = require('cookie-session');

app.use(cookieSession({
  keys: ['key1', 'key2']
}));

#9


1  

When u use http request on client side, remember to attach credentials. In Angular2 you need to add option argument: { withCredentials: true }. After this you will have the same req.sessionID until you reset it again.

当您在客户端使用http请求时,请记住附加凭据。在Angular2中,您需要添加选项参数:{withCredentials: true}。之后你会得到同样的回复。sessionID直到您再次重置它。

this._http.get("endpoint/something", { withCredentials: true })

#10


0  

If your middleware stack is unclear, assuming you have session middleware somewhere, you can save the session before the redirect:

如果您的中间件堆栈不清楚,假设您在某处有会话中间件,您可以在重定向之前保存会话:

if (req.user) {
    req.session.save(function (err) {
        if (err) {
            // ... panic!
        }
        res.redirect("/user/" + req.user._id);
    });
    return;
}

#11


0  

Have you tried to insert in the cookieParser your secretKey?

您是否尝试过在cookieParser中插入您的分泌键?

var passport = require('passport');
var expressSession = require('express-session');

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser('mySecretKey'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressSession({
secret: 'mySecretKey',
  resave: false,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

#12


0  

Mine was about cookies & cors. I solved by adding following code to my server:

我的是饼干公司。我通过向我的服务器添加以下代码来解决:

allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); // your website
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' === req.method) {
    res.send(200);
} else {
    next();
}};

#13


0  

Had exactly the same problem. For me, the solution was to use "client-sessions" instead of 'express-session". Probably bad sessions configuration?

也有同样的问题。对我来说,解决方案是使用“客户端会话”而不是“表达会话”。可能坏会话配置?

Not working code:

不是工作代码:

var session = require('express-session');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(session({
    secret: 'random string',
    resave: true,
    saveUninitialized: true,
    cookie: { secure: true }
}));

Working code:

工作代码:

var session = require('client-sessions');

        app.use(bodyParser.urlencoded({ extended: false }));
        app.use(express.static(path.join(__dirname, 'public')));
        app.use(cookieParser());
        app.use(bodyParser.json());
        app.use(session({
        cookieName: 'session',
        secret: 'random string',
        duration: 30 * 60 * 1000,
        activeDuration: 5 * 60 * 1000,
    }));

#14


0  

Once you have your express session setup make sure you have passport serialize & deserialize, in the deserialize function that's when req.user gets generated. See explanation here from another * question.

一旦您有了快速会话设置,请确保您在req的反序列化函数中有passport序列化和反序列化。用户生成。这里是另一个*问题的解释。

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


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

#15


-1  

I had a different issue, something with bcrpt-node and arrow functions.

我有一个不同的问题,关于bcrpt-node和arrow函数。

Code that works:

代码:

userSchema.methods.generateHash = function (password) {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); 
};

userSchema.methods.isValidPassword = function (password) {
  return bcrypt.compareSync(password, this.password);
};

Code that does not work:

不工作的代码:

userSchema.methods.generateHash = (password) => {
  return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

userSchema.methods.isValidPassword = (password) => {
  return bcrypt.compareSync(password, this.password);
};