因此,我在使用 Restify 和 Passportjs(Google OAuth2 策略)时遇到了 Node.js 应用程序的问题。当我使用passport.authenticate()
,它给了我以下错误:
400. 这是一个错误。
错误:无效_请求
缺少必需参数:范围
几年前我发现了关于同一件事的另一个问题(invalid_request 缺失:在 Google Oauth2 上使用 Google Passportjs 的范围 https://stackoverflow.com/questions/34931847/invalid-request-with-missing-scope-using-google-passportjs-on-google-oauth2?newreg=02cf8c8315244b2e8b2a1aefcb4ebc3a)。作者说他最终自己修复了这个问题,但没有发布修复结果。
还有其他人遇到过这个问题并能够解决它吗?我想不通。这是我的代码:
authController.js
var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth20').Strategy;
var auth = {
google: {
clientID: '<ID>',
clientSecret: '<SECRET>',
callbackURL: 'https://localhost:8080/auth/google/return',
scope: ['profile', 'email']
}
};
passport.use(new GoogleStrategy({
clientID: auth.google.clientID,
clientSecret: auth.google.clientSecret,
callbackURL: auth.google.callbackURL
}, function(accessToken, refreshToken, profile, cb) {
return cb(null, profile.id);
}));
module.exports.authenticate = passport.authenticate('google', { scope: auth.google.scope });
module.exports.isAuthenticated = passport.authenticate('google', { successRedirect: '/hello/succeed', failureRedirect: '/hello/fail' });
服务器.js
var restify = require('restify'),
fs = require('fs'),
bodyParser = require('body-parser'),
authController = require('./controllers/authController');
// Placeholder handler.
function respond(req, res, next) {
res.send('hello ' + req.params.name);
return next();
}
// Create server.
var api = restify.createServer({
certificate: fs.readFileSync('server.crt'),
key: fs.readFileSync('server.key'),
name: 'BQ:IQ Question Writer'
});
// Setup authentication
api.get('/auth/google', authController.authenticate);
api.get('/auth/google/return', authController.isAuthenticated);
// Setup routes.
api.get('/hello/:name', respond);
api.head('/hello/:name', respond);
api.listen(8080, function() {
console.log('%s listening at %s', api.name, api.url);
});