从未调用过Passer deserializeUser,req.isAuthenticated始终为false(使用res.redirect)

时间:2019-03-08 03:54:13

标签: node.js express passport.js

我希望您可以帮助我解决这个问题,因为我对护照和快递还不熟悉。我在身份验证方面遇到问题,这是我的代码...

设置会话:

// required for passport session
app.use(expressSession({
  secret: 'mySecret',
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week
    secure: false
  },
  saveUninitialized: false,
  resave: false
}));
app.use(passport.initialize());
app.use(passport.session());

// Add headers
app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', '*');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept");

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  next();
});

app.use(bodyParser.json());

// Authentication
var authRoute = require("./Routes/AuthRoute");
app.use('/api', authRoute);

// Activities
var activityRoute = require("./Routes/ActivityRoute");
app.use('/api', activityRoute);

登录路由(位于AuthRoute.js内部):

  router.post('/login', 
    function(request, response, next) {
        console.log(request.session)
        passport.authenticate('login', 
        function(err, user, info) {
            if(!user){ response.send(info.message);}
            else{

                request.login(user, function(error) {
                    if (error) return next(error);
                    console.log("Request Login successful.");
                    return response.send('Login successful');
                });
            }

        })(request, response, next);
    }
);

在外部站点身份验证之后对我的/ login端点进行的调用,如果成功,该调用将重定向到我的/ activities端点:

exports.stravaAuthenticateRedirect = function (req, res) {

        var code = req.query.code;
        var uri = "https://www.strava.com/oauth/token?client_id=" + process.env.STRAVA_CLIENT_ID + "&client_secret=" + process.env.STRAVA_CLIENT_SECRET + "&code=" + code;
        request.post(uri, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
                var jsonData = JSON.parse(body);
                var accessToken = jsonData['access_token'];
                var username = jsonData['athlete']['username'];
                var requestData = { "username": username, "strava_access_token": accessToken };
                // Call made to /login route
                request({
                    url: process.env.BASE_API_URL + "login",
                    method: "POST",
                    json: requestData
                }, function (error, response, body) {
                    if (!error && response.statusCode === 200) {
                        res.redirect(process.env.BASE_API_URL + "activities");
                    }
                    else {
                        console.log("error: " + error)
                        //TODO: Redirect to error page.
                        return error;
                    }
                })
            }
        });
    }

Passport LocalStrategy:

passport.use('login', new LocalStrategy({
    usernameField: 'username',
    passwordField: 'strava_access_token'
},
    function (username, strava_access_token, callback) {
        var query = "SELECT * FROM user WHERE username = ?;";
        db.query(query, [username], function (err, result) {
            if (err) throw err;
            if (result.length < 1) {
                query = "INSERT INTO user set username = ?, strava_access_token = ?;";
                db.query(query, [username, strava_access_token], function (err, result) {
                    jsonResult = JSON.stringify(result);
                    if (result.insertId == 'undefined') {
                        return callback(null, false, { message: 'Error logging in, issue: creating new user.' });
                    }
                    var jsonUser = {
                        "id": result.insertId,
                        "username": username,
                        "strava_access_token": strava_access_token
                    };
                    return callback(null, JSON.stringify(jsonUser), { message: 'New user created.  Logged in successfully.' });
                })
            } else {
                var jsonResult = JSON.stringify(result[0]);
                console.log("JSON result is:" + jsonResult);
                return callback(null, jsonResult, { message: 'Logged in Successfully.' });
            }
        });
    }
));

序列化和反序列化(从不调用deserializeUser):

passport.serializeUser(function (user, done) {
    done(null, JSON.parse(user)['id']);
});

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

活动端点,该端点在成功登录后(在ActivityRoute.js内部)被调用:

var isAuthenticated = function (req, res, next) {
    if (req.isAuthenticated())
        return next();
    res.redirect(process.env.BASE_CLIENT_URL + 'login');
}

router.get('/activities', isAuthenticated, activityController.getActivities);

在调用/ activities端点时,我可以看到req.sessionStore.sessions具有具有正确用户ID的活动会话,但是isAuthenticated始终返回false。任何想法可能是什么原因造成的?可能是对我的活动端点的res.redirect调用是问题吗?关于为什么从不调用deserializeUser的任何想法?

谢谢!

0 个答案:

没有答案