2016-04-02 8 views
0

req.userを社会的認証の後で未定義にすることに関する多くの質問がありますが、何もわかりませんでした。req.user明示的なサーバーを使用してtwitter認証を行った後、passport.js

私は、twitter認証にパスポートを使用する例を正常に使用できました:https://github.com/passport/express-4.x-twitter-example。私はできるだけこのパターンに従おうとしましたが、うまく動作するように見えません。

特に、私は正常に認証できますが、req.userは未定義です。私のユーザデータがこの例から何の問題も返されなかったので、これは意味をなさない。

ミドルウェアが例で使用されているのと同じだから、これはミドルウェアの問題だと思う気がしません。複数のドメインを持つことには何かがあるかもしれませんが、私は何がわかりません。これはすべてローカルホスト上で行われています。ツイッターで

のウェブサイトがあるように、アプリが設定されている: 127.0.0.1:3000/signinと コールバックURLは次のとおりです。あなたのよう127.0.0.1:2999/auth/twitter/return

私のクライアントはポート3000で作業しており、ポート2999で稼働しているサーバーを呼び出しています。

コードを簡単に見てみると、127.0.0.1:3000/signinのクライアントには、 〜127.0.0.1:2999/auth/twitterに変更し、認証要求を開始します。フードの下では、エクスプレスサーバーはserver/index.js - serverに作成されます。これはroutes/index.js内のルートをインポートします。その中には、コントローラauthenticate.jsが処理するものもあります。ご覧のとおり、oauth twitterのリクエストはauthenticate.jsで行われます。ここでも、認証は正常に進み、127.0.0.1:3000/searchにリダイレクトされます。しかし、this.twitter_callbackでわかるように、私はreq.userを印刷しています。それは未定義です。

私のコードからコンシューマキー/シークレットを編集したことに注意してください。

サーバ/ 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 

ルート/ 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

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 

すべてのヘルプは大きく、非常に高く評価されるだろう。

答えて

0

twitter_callbackルートがどのように指定されたかに問題がありました。

私はこれにコールバックを変更する場合:

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を使わずに、エクスポートするために書き直す方法を正確にはわからない

関連する問題