使用快递服务器,passport.js进行Twitter身份验证后,req.user未定义 [英] req.user undefined after twitter authentication using express sever, passport.js

查看:60
本文介绍了使用快递服务器,passport.js进行Twitter身份验证后,req.user未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题与在社交身份验证后获取未定义的req.user有关,但是我发现没有任何问题可以帮助我.

There are many questions relating to getting a req.user undefined after social authentication, but I found none which could help me.

我已经成功地使用了使用护照进行Twitter身份验证的示例:https://github.com/passport/express-4.x-twitter-example .我试图尽可能地遵循这种模式,但似乎无法使其正常工作.

I have been able to successfully use the example for using passport for twitter authentication: https://github.com/passport/express-4.x-twitter-example. I tried to follow this pattern as closely as possible but cannot seem to get it to work.

具体地说,我能够成功进行身份验证,但是req.user是未定义的.这对我来说毫无意义,因为示例中返回的我的用户数据没有问题.

Specifically, I am able to successfully authenticate, but the req.user is undefined. This makes no sense to me as my user data was returned no problem from the example.

我不倾向于认为这是一个中间件问题(就像其他人一样),因为中间件与示例中使用的相同.可能有多个域,但是我不确定.所有这些都是在本地主机上完成的.

I'm not inclined to believe this is a middleware problem (as it has been for others) as the middleware is the same as that used in the example. It could be something about having multiple domains, but I'm not sure what. All of this is being done on the localhost.

在Twitter中,该应用程序已设置为网站是:127.0.0.1:3000/登录和回调网址是:127.0.0.1:2999/auth/twitter/return

In Twitter, the app is set up so that website is: 127.0.0.1:3000/signin and the callback url is: 127.0.0.1:2999/auth/twitter/return

您可以看到,我的客户端正在使用端口3000,并且正在对在端口2999上运行的服务器进行呼叫.

As you can tell, my client is working on port 3000 and it is making calls to a server running on port 2999.

为简要介绍代码,位于127.0.0.1:3000/signin上的客户端具有一个链接至127.0.0.1:2999/auth/twitter的按钮,从而启动了身份验证请求.在后台,快速服务器是在server/index.js--server中创建的.这会将路由导入到route/index.js中,其中的某些路由由controller authenticate.js处理.如您所见,oauth twitter请求是在authenticate.js中发出的.再次,身份验证成功进行,我被重定向到127.0.0.1:3000/search.但是,正如您在this.twitter_callback中看到的那样,我正在打印req.user,它是未定义的.

To briefly walk you through the code, the client on 127.0.0.1:3000/signin has a button which links to 127.0.0.1:2999/auth/twitter, thus initiating the authentication request. Under the hood, the express server is created in server/index.js--server. This imports the routes in routes/index.js, some of which the controller authenticate.js handles. As you can see, the oauth twitter request is made in authenticate.js. Again, authentication proceeds successfully, I am redirected to 127.0.0.1:3000/search. However, as you can see in this.twitter_callback, I am printing the req.user and it is undefined.

请注意,我已从代码中删除了使用者密钥/秘密.

Please note that I have redacted the consumer key/secret from my code.

server/index.js

server/index.js

var cors = require('cors')
var bodyParser = require('body-parser')
var express = require('express');
var app = express();
var http = require('http').Server(app)
var io = require('socket.io')(http)
// NOT SURE WHY I NEED TO GO BACK 3 FOLDERS TO GET TO PORT_CONFIG
var port = require("../port_config.json").server_port;
var PORT = Number(process.env.PORT || port);
var routes = require('./routes/index.js')
var database = require('./database/db.js')
var db = new database()

app.use(cors()); // middleware that allows cross-platform requests
app.use(bodyParser.json());

db.dbConnect(function(err,db_instance){
    // routes
    routes(app, db_instance, io)
    // send user polls on connection 
    // TEMPORARY (WILL BE GRABBED ON LOGIN)
    var user = null // WILL BE SET AFTER LOGIN
    io.on('connection', function(socket) {
    var places_attending = db_instance.collection('places_attending')
    places_attending.find({}).toArray(function(err,docs){
        var places_user_attending = docs.map(doc => {
            if (doc.attending.indexOf(user) !== -1) {
                return {
                    id: doc.id,
                    name: doc.name,
                    num_attending: doc.attending.length
                }
            }
        })
        socket.emit('places_user_attending', places_user_attending);
    })
    })
})

http.listen(PORT, function () {
    console.log('Backend server listening at http://localhost:' +     PORT);
})

module.exports = http

routes/index.js

routes/index.js

var Search = require('../controllers/search.js')
var Add = require('../controllers/add.js')
var Authenticate = require('../controllers/authenticate.js')


module.exports = function(app, db, io) {
    var search = new Search(db, io)
    var add = new Add(db, io)
    var authenticate = new Authenticate(app)

    app.route('/api/search')
        .post(search.search_yelp)

    app.route('/api/add')
        .post(add.add_attendee)

    app.route('/auth/twitter')
        .get(authenticate.twitter_authentication) 

    app.route('/auth/twitter/return')
        .get(authenticate.twitter_callback)
}

authenticate.js

authenticate.js

function authenticate(app) {

var passport = require('passport');
var Strategy = require('passport-twitter').Strategy;


// Configure the Twitter strategy for use by Passport.
passport.use(new Strategy({
    consumerKey: REDACTED,
    consumerSecret: REDACTED,
    callbackURL: 'http://127.0.0.1:2999/auth/twitter/return'
  },
  function(token, tokenSecret, profile, cb) {
    // In this example, the user's Twitter profile is supplied as the user
    // record.  In a production-quality application, the Twitter profile should
    // be associated with a user record in the application's database, which
    // allows for account linking and authentication with other identity
    // providers.
    return cb(null, profile);
  }));


// Configure Passport authenticated session persistence.
passport.serializeUser(function(user, cb) {
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});


// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave:     true, saveUninitialized: true }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

this.twitter_authentication = passport.authenticate('twitter')

this.twitter_callback = (
  passport.authenticate('twitter', { failureRedirect: 'http://127.0.0.1:3000/signin' }),
  function(req, res) {
       console.log('REQ.USER OBJECT: ' + req.user)
       res.redirect('http://127.0.0.1:3000/search');
   }
)

}

module.exports = authenticate

任何帮助将不胜感激.

推荐答案

问题在于如何指定我的twitter_callback路由.

The problem was in how my twitter_callback route was specified.

如果我将回调更改为此:

If I change the callback to this:

this.twitter_callback = app.get('/auth/twitter/return',
passport.authenticate('twitter', { failureRedirect: 'http://127.0.0.1:3000/signin' }),
function(req, res) {
console.log(req.user)
res.redirect('http://127.0.0.1:3000/search');
})

一切正常.我认为这与中间件在最初编写时未正确应用有关.不完全确定如何将其重写以导出它,而不必在twitter_callback中使用app.get

everything works fine. I think this has something to do with the middleware not being applied correctly the initial way I wrote it. Not exactly sure how I would rewrite it to export it, without using app.get in the twitter_callback though

这篇关于使用快递服务器,passport.js进行Twitter身份验证后,req.user未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆