node.js - Passport 不会保存在 session 变量中。导航后 req.user 不存在

标签 node.js session nodes passport.js

背景:

我有一个在端口 4200 上运行的 Angular-cli,以及在 3000 端口上运行的服务器端 API Node.js。

我发现使用本地 Passport 登录后, session Passport 值不会保存。

因此,当我登录后尝试导航到另一个页面时,它没有持有 Passport , session 中的变量按预期需要调用req.user

由于某种原因,服务器没有调用反序列化用户。

Req.user 登录并重定向到页面/test 后将无法工作。

更新:

要登录,我使用端口 4200 从站点发送请求,代码如下:(angular2/4)

performLogin(name: string, password: string): Observable<Comment[]> {
    var params = new URLSearchParams();
    params.append('username', name);
    params.append('password', password);
  url = "SITE:3000/api/login";

    return this.http.post(this.url,params, this.options)
        .map(result => result.json())
        .do(result => this.result = result);
  }

更新 2:插入信用请求客户端。 在每次登录请求 -> 然后调用测试页面时,我总是得到:

ReferenceError: User is not defined
    at /root/mafiagame/src/config/passport.js:32:9
    at pass (/usr/lib/node_modules/passport/lib/authenticator.js:347:9)
    at Authenticator.deserializeUser (/usr/lib/node_modules/passport/lib/authenticator.js:352:5)
    at SessionStrategy.authenticate (/usr/lib/node_modules/passport/lib/strategies/session.js:53:28)
    at attempt (/usr/lib/node_modules/passport/lib/middleware/authenticate.js:348:16)
    at authenticate (/usr/lib/node_modules/passport/lib/middleware/authenticate.js:349:7)
    at Layer.handle [as handle_request] (/root/mafiagame/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/root/mafiagame/node_modules/express/lib/router/index.js:317:13)
    at /root/mafiagame/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/root/mafiagame/node_modules/express/lib/router/index.js:335:12)
    at next (/root/mafiagame/node_modules/express/lib/router/index.js:275:10)
    at initialize (/usr/lib/node_modules/passport/lib/middleware/initialize.js:53:5)
    at Layer.handle [as handle_request] (/root/mafiagame/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/root/mafiagame/node_modules/express/lib/router/index.js:317:13)
    at /root/mafiagame/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/root/mafiagame/node_modules/express/lib/router/index.js:335:12)

相关问题,但没有解决我的问题:

Passportjs not saving user into session after login

PassportJS deserializeUser never called

Express Passport Session not working

req.session.passport is empty, deserializeUser not called - ExpressJS, Passport

主要问题: Req.user 登录并重定向到页面/test 后将无法工作。

似乎 session 已保存,但该 session 中的 Passport 详细信息并未保存。

我的申请:

登录后转储req.session:

 Session {
      cookie:
       { path: '/',
         _expires: 2017-05-03T19:42:58.728Z,
         originalMaxAge: 14400000,
         httpOnly: true,
         secure: false },
      passport: { user: '5909a6c0c5a41d13340ecf94' } }

访问/test时的 session

Session {
  cookie:
   { path: '/',
     _expires: 2017-05-03T19:43:10.503Z,
     originalMaxAge: 14400000,
     httpOnly: true,
     secure: false } }

server.js

这是我的 server.js,其中包含 express 、 Passport 等。

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session      = require('express-session');
var router = express.Router();
var Account = require('src/app/models/Users.js');
var Core = require('src/app/gamemodels/core');
// Init passport authentication
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
require('src/config/passport')(passport);
var cookieParser = require('cookie-parser')


app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    if ('OPTIONS' == req.method) {
        res.send(200);
    } else {
        next();
    }
});


// required for passport session

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mongoose.connect('database');
app.use(cookieParser()) // required before session.

app.use(session({
    secret: 'xxx',
    cookie: {
        secure: false
    }}));

app.use(passport.initialize());
app.use(passport.session());



console.log(mongoose.connection.readyState);
app.use(function (req, res, next) {
    console.log('Time:', Date.now());

   // core.loggameRequest();
    next();
});


var port = process.env.PORT || 3000;        // set our port


// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ text: 'hooray! welcome to our api!' });
});


router.get('/test', function(req,res) {
    console.log(req.user);
    res.json(req.user);
});

router.get("/getuser", function(req,res) {
    Account.findOne({}, function (err,response) {
        console.log("starting core...");
        console.log(Core);
        console.log("core log end");
    //    Core.experienceToRankDetails(response.xp,'female');
        console.log("executed!");
     //   res.json(response);
        Core.experienceToRankDetails(response.xp,'female').then(function (result) {

            res.json({user: response, rank: result});

        });

    });
});

router.get('/onlinestate', function(req,res) {
    if (req.user) {
        res.json(true);

    } else {
        res.json(false);
    }
});


router.post('/signup', passport.authenticate('local-signup', {
    successRedirect : '/profile', // redirect to the secure profile section
    failureRedirect : '/signup', // redirect back to the signup page if there is an error
}));

router.post('/login', passport.authenticate('local-login'), function(req, res) {

    console.log("executed login!");
    console.log(req.user);
    req.session.user = req.user;
    req.logIn(req.user, function (err) { // have this in passport login too, but tried it here too .
        if (err) {
            return next(err);
        }

    });

});

/*
router.post('/login', function(req,res) {
    console.log("routing post login");
    console.log(req.body);
    console.log(req.user);

    var username = req.body.username;
    var password = 0;
    console.log("using passport");
    passport.authenticate('local', {failureRedirect: '/login'}, function (req, res) {
        console.log("performed!");
        res.redirect('/');
    });






});
*/



// more routes for our API will happen here

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);



*/
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

Passport :

// config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

// load up the user model
var Account = require('src/app/models/Users.js');

// expose this function to our app using module.exports
module.exports = function(passport) {

    passport.serializeUser(
        function(user, done){
            console.log("serialize");
            done(null, user.id);
        });

    passport.deserializeUser(
        function(id, done){
            console.log("deserialize " + id);
            Account.findById(id, function(err, user){
                if(err){
                    done(err);
                }
                done(null, user);
            });
        });
    passport.use('local-login', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'username',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) { // callback with email and password from our form
            console.log("doing local login");
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            Account.findOne({ 'username' :  username }, function(err, user) {
                var thisuser = user;
                console.log("query account is done");
                // if there are any errors, return the error before anything else
                if (err) {
                    console.log("error occured");
                    return done(err);
                }

                console.log("if user exist check");


                // if no user is found, return the message
                if (!user)
                    return done(null, false,'No user found.'); // req.flash is the way to set flashdata using connect-flash


                console.log("checking password");
                // if the user is found but the password is wrong
                if (!user.validPassword(password)) {
                    console.log("password is not valid");
                    return done(null, false, 'Oops! Wrong password.'); // create the loginMessage and save it to session as flashdata

                }
                console.log("all good! logging in!");


                req.login(thisuser, function(error) {
                    if (error) return next(error);
                    console.log(error);

                    console.log("Request Login supossedly successful.");
                });

                // all is well, return successful user
                return done(null, thisuser);
            });

        }));

    passport.use('local-signup', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'email',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, username, password, done) {
            process.nextTick(function() {
                    console.log("doing local signup");
                // find a user whose email is the same as the forms email
                // we are checking to see if the user trying to login already exists
                Account.findOne({ 'username' :  username }, function(err, user) {
                    // if there are any errors, return the error
                    if (err)
                        return done(err);

                    // check to see if theres already a user with that email
                    if (user) {
                        return done(null, false, 'That username is already taken.');
                    } else {

                        var newUser            = new Account();

                        // set the user's local credentials
                        newUser.username    = username;
                        newUser.password = newUser.encryptPassword(password);

                        // save the user
                        newUser.save(function(err) {
                            if (err)
                                throw err;
                            return done(null, newUser);
                        });
                    }

                });

            });

        }));

};

用户变量包含:

{ _id: 5909a6c0c5a41d13340ecf94,
  password: '$2a$10$tuca/t4HJex8Ucx878ReOesICV6oJoS3AgYc.LxQqCwKSV8I3PenC',
  username: 'admin',
  __v: 0,
  inFamily: false,
  bank: 500000,
  cash: 1,
  xp: 0,
  rank: 1,
  bullets: 0,
  location: 1,
  permission: 0,
  health: 100 }

登录后服务器的响应:(发布到/login 路由)

doing local login
query account is done
if user exist check
checking password
all good! logging in!
serialize
undefined
Request Login supossedly successful.
serialize
executed login!
{ _id: 5909a6c0c5a41d13340ecf94,
  password: '$2a$10$tuca/t4HJex8Ucx878ReOesICV6oJoS3AgYc.LxQqCwKSV8I3PenC',
  username: 'admin',
  __v: 0,
  inFamily: false,
  bank: 500000,
  cash: 1,
  xp: 0,
   rank: 1,
  bullets: 0,
  location: 1,
   permission: 0,
  health: 100 }
serialize

访问/test 的服务器响应

undefined

最佳答案

这似乎是一个角度 2/4 的问题。你可以试试这个thisthis

希望对您有帮助! :-)

关于node.js - Passport 不会保存在 session 变量中。导航后 req.user 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762374/

相关文章:

javascript - 无法获取 Node 中解码后的base64数据的值

C# 测试修改后的 session 变量

java - 如何使用compareTo()方法比较List中的对象?

javascript - 通过 express 从 mongo 获取数据,构建对象,并发送给 React

javascript - 如何编写任意长的Promise链

node.js - 如何在 Windows 7 中删除 git 本地存储库文件夹

python - CherryPy 与 Postgresql session

php - 使用 id 检查 session 数据,并在循环内更改 id

java - 服务器节点之间如何同步数据?

c - 制作一个 cpnode 函数?