-->

Error: invalid_request Missing required parameter:

2019-07-20 04:25发布

问题:

So, I've run into a problem with my Node.js app, using Restify and Passportjs (Google OAuth2 strategy). When I use passport.authenticate(), it gives me the following error:

400. That’s an error.
Error: invalid_request
Missing required parameter: scope

I found another question about the same thing from a couple of years ago (invalid_request with missing: scope using Google Passportjs on Google Oauth2). The author said he finally fixed it himself but didn't post the fix.

Has anyone else run into this and been able to fix it? I can't figure it out. Here is my code:

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' });

server.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);
});

回答1:

Seems I was missing the following code after initializing the server:

api.use(restify.plugins.queryParser({ mapParams: false }));

Once I added that line, I no longer saw the Google error, and the process passed back to my code.