我使用以下代码对使用护照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)
导致此问题的原因是什么?如何解决此问题? 任何帮助都会很棒。感谢。
答案 0 :(得分:2)
用于处理FB回调的路由应该只发出重定向(如果身份验证失败,则返回登录页面,或者当身份验证成功时返回“登录”页面。)
您正在调用routes.loggedin
来处理该路由(如果成功):
app.get('/fbauthed', passport.authenticate('facebook',{ failureRedirect: '/'}), routes.loggedin);
这将保留FB在FB中传递的所有令牌,从而导致“此授权码已被使用”消息。
所以试试这个:
app.get('/loggedin', ensureLoggedIn('/'), routes.loggedin); // see below
app.get('/fbauthed', passport.authenticate('facebook',{
failureRedirect: '/',
successRedirect: '/loggedin'
}));
ensureLoggedIn
是一个中间件,用于检查用户是否已登录,如果没有,将重定向到/
(或您喜欢的任何URL)。