2

我正在使用以下代码使用护照 js 对用户进行身份验证

/**
 * Module dependencies.
 */

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

var config = require('./config');

var User = require('./models/user');

var passport = require('passport'),
    FacebookStrategy = require('passport-facebook').Strategy;

//setting up passport
passport.serializeUser(function(user, done){
    done(null, user.id);
});

passport.deserializeUser(function(id, done){
    User.findById(id, function(err, user){
        done(err, user);
    });
});


passport.use(new FacebookStrategy({
        clientID: config.development.fb.appid,
        clientSecret: config.development.fb.appSecret,
        callbackURL: config.development.fb.url + 'fbauthed'
    },

    function (accessToken, refreshToken, profile, done) {
        User.findOne({
            'fbId': profile.id
        }, function (err, oldUser) {
            if (oldUser) {
                console.log('Existing user: ' + oldUser.name + ' found and logged in');
                done(null, oldUser);
            } else {
                var newUser = new User();
                newUser.fbId = profile.id;
                newUser.name = profile.displayName;
                newUser.email = profile.emails[0].value;
                newUser.username = profile.username;
                console.log(profile);

                newUser.save(function (err) {
                    if (err) throw err;
                    console.log('New user:' + newUser.name + 'created and logged in');
                    done(null, newUser);
                });
            }
        });
    }

));


app.configure(function(){
    app.set('port', process.env.PORT || 5000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.cookieParser());
    app.use(express.session({secret: 'big secret'}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
    app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/fbauth', passport.authenticate('facebook', {scope: 'email'}));
app.get('/fbauthed', passport.authenticate('facebook',{ failureRedirect: '/'}), routes.loggedin);

app.get('/logout', function(req,res){
    req.logOut();
    res.redirect('/');
});
//app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
});

上面的代码在用户进行身份验证时非常有用,但是在身份验证后页面刷新会引发如下错误。

Express
500 failed to obtain access token (status: 400 data: {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}})
at /home/colm/javascript/facebookauth/node_modules/passport-facebook/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth2.js:125:38
at exports.OAuth2.getOAuthAccessToken (/home/colm/javascript/facebookauth/node_modules/passport-facebook/node_modules/passport-oauth/node_modules/oauth/lib/oauth2.js:131:18)
at passBackControl (/home/colm/javascript/facebookauth/node_modules/passport-facebook/node_modules/passport-oauth/node_modules/oauth/lib/oauth2.js:77:9)
at IncomingMessage.exports.OAuth2._request.request.on.callbackCalled (/home/colm/javascript/facebookauth/node_modules/passport-facebook/node_modules/passport-oauth/node_modules/oauth/lib/oauth2.js:94:7)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at CleartextStream.socketOnData [as ondata] (http.js:1447:20)
at CleartextStream.CryptoStream._push (tls.js:544:27)
at SecurePair.cycle (tls.js:898:20)

是什么原因造成的,我该如何解决这个问题?任何帮助都会很棒。谢谢。

4

1 回答 1

3

用于处理 FB 回调的路由应该只发出重定向(如果身份验证失败返回登录页面,或者身份验证成功时返回“登录”页面)。

您正在调用routes.loggedin处理该路线(如果成功):

app.get('/fbauthed', passport.authenticate('facebook',{ failureRedirect: '/'}), routes.loggedin);

这会将 FB 传递的所有令牌保留在 URL 中,从而导致“此授权代码已被使用”消息。

所以试试这个:

app.get('/loggedin', ensureLoggedIn('/'), routes.loggedin); // see below
app.get('/fbauthed', passport.authenticate('facebook',{ 
  failureRedirect: '/',
  successRedirect: '/loggedin'
}));

ensureLoggedIn是一个中间件,它将检查用户是否登录,如果没有,将重定向到/(或您喜欢的任何 URL)。

于 2013-03-26T14:21:41.240 回答