在nodejs中使用twitter oauth时无法进行GET / auth / twitter / callback

时间:2013-10-15 20:14:30

标签: javascript node.js oauth passport.js passport-twitter

我正在尝试使用passportjs在nodejs中进行twitter oauth但是收到错误

Cannot GET /auth/twitter/callback?oauth_token=alksdkalsjdsjd23232378skjdfjsdhf&oauth_verifier=234jjh23j4k234k23h4j2h342k34hj

这是我的节点js代码

    var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , GoogleStrategy = require('passport-google').Strategy
  , TwitterStrategy = require('passport-twitter').Strategy;


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

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


passport.use(new TwitterStrategy({
    consumerKey: 'xxxxxxxxxxxxxxxxxxxx',
    consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'
},
 function(token, tokenSecret, profile, done) {
     process.nextTick(function () {
      return done(null, profile);
    });
 }
 ));


var app = express();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/../../public'));
});


app.get('/', function(req, res){
  res.render('index', { user: req.user });
});



app.get('/login', function(req, res){
  res.sendfile('./views/auth.html');
});




app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('auth/twitter/callback',
  passport.authenticate('twitter', { successRedirect: '/success',
                     failureRedirect: '/login' }));

app.get('/success', function(req, res){
    res.send("success logged in");
});

app.listen(process.env.PORT || 3000);

2 个答案:

答案 0 :(得分:2)

修改 /路由定义中缺少auth/twitter/callback

同样对于路由器/auth/twitterauth/twitter/callbackpassport.authenticate()作为中间件将进行身份验证,您应该具有路由处理功能。

因此,路线的定义应如下所示:

app.get('/auth/twitter', 
         passport.authenticate('twitter'),
         function(req, res) {}); // empty route handler function, it won't be triggered
app.get('/auth/twitter/callback', 
         passport.authenticate('twitter', { 
                                successRedirect: '/success',
                                failureRedirect: '/login' }),
         function(req, res) {}); // route handler

答案 1 :(得分:0)

您不需要空路由处理程序function(req, res) {} - 您可以将参数保留,并且表达将理解您不打算使用处理程序