Google-api-nodejs-client: setCredentials is not a function in v23

Created on 22 Nov 2017  路  14Comments  路  Source: googleapis/google-api-nodejs-client

Hi,

Some code between version 22 and version 23 has deleted the setCredentials function.

I was getting setCredentials is not a function while trying to use this library to authenticate/access apis. This could be downstream, idk.

The readme does contain references to this function.

screen shot 2017-11-22 at 1 32 53 pm

screen shot 2017-11-22 at 1 32 58 pm

Most helpful comment

@MySidesTheyAreGone apologies for the break here. We have a fix coming. In the interim - you can work around this by just assigning a credentials object like this:

oAuth2Client.credentials = credentials

It's the same thing, just doing assignment instead of using the setCredentials method.

All 14 comments

Hi,

I recently discovered the same issue and following code worked for me. I think there is some change in version 22 or 23 and now you can use oauth2Client.credentials = tokens in place of oauth2Client.setCredentials(tokens) to set the tokens/credentials.

Below is a working sample code. Sample code is adapted from https://github.com/google/google-api-nodejs-client/blob/master/samples/oauth2.js

// Copyright 2012-2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

var readline = require('readline');

var google = require('googleapis');
var googleAuth = require('google-auth-library');

var auth = new googleAuth();
var OAuth2Client = auth.OAuth2;
var plus = google.plus('v1');

// Client ID and client secret are available at
// https://code.google.com/apis/console
var CLIENT_ID = ''; // removed for posting to GitHub
var CLIENT_SECRET = ''; // removed for posting to GitHub
var REDIRECT_URL = 'https://developers.google.com/oauthplayground';

var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function getAccessToken (oauth2Client, callback) {
  // generate consent page url
  var url = oauth2Client.generateAuthUrl({
    access_type: 'offline', // will return a refresh token
    scope: 'https://www.googleapis.com/auth/plus.me' // can be a space-delimited string or an array of scopes
  });

  console.log('Visit the url: ', url);
  rl.question('Enter the code here:', function (code) {
    // request access token
    oauth2Client.getToken(code, function (err, tokens) {
      if (err) {
        return callback(err);
      }
      // set tokens to the client
      // TODO: tokens should be set by OAuth2 client.
      oauth2Client.credentials = tokens;
      callback();
    });
  });
}

// retrieve an access token
getAccessToken(oauth2Client, function () {
  // retrieve user profile
  var res = plus.people.get({ userId: 'me', auth: oauth2Client }, function (err, profile) {
    if (err) {
      return console.log('An error occured', err);
    }
    console.log(profile.displayName, ':', profile.tagline);
  });
});

Hope it helps! Thank you.

Thanks Justin for fixing this , can you please let us know when the fix for this will be available - in what version? Our tests and deployment are blocked due to this issue.

Dear Google,

I am completely $#@%!&.

Please fix this yesterday.

Regards,
My Sides

@MySidesTheyAreGone apologies for the break here. We have a fix coming. In the interim - you can work around this by just assigning a credentials object like this:

oAuth2Client.credentials = credentials

It's the same thing, just doing assignment instead of using the setCredentials method.

Thanks Justin, I patched it as you said for the time being, it's good enough to keep developing. I was being facetious, of course; I'm a complete amateur and I've done much worse. Have a good day!

@JustinBeckwith : Hi, thank you.
I followed your solution here:

GoogleTokens.findOne({isObsolete: false}).then((token) => {
                oauth2Client.credentials = {
                    access_token: token.accessToken,
                    refresh_token: token.refreshToken,
                    token_type: "Bearer",
                    expiry_date: token.expiryDate
                };

                var androidpublisher = google.androidpublisher('v2');

                var params = {
                    packageName: req.query.packageName,
                    subscriptionId: req.query.subscriptionId,
                    token: req.query.token
                };

                androidpublisher.purchases.subscriptions.get(params, function (err, response) {
                    if (err) {
                        console.log('Encountered error', err);
                    } else {
                        res.success(response);
                    }
                });
            });

I'm sure the "token" variable retrieved from database contains correct information and token is not expired yet.

I tried to get data from this service subscriptions.get

And I got error

Error: No access, refresh token or API key is set.

Do you know what is the problem here?
Thanks

I tried to call Google API using request, and it works properly

GoogleTokens.findOne({isObsolete: false}).then((token) => {
                let subscriptionsGetUrl = "https://www.googleapis.com/androidpublisher/v2/applications/" + req.query.packageName + "/purchases/subscriptions/" + req.query.subscriptionId + "/tokens/" + req.query.token + "?access_token=" + token.accessToken;

                request(subscriptionsGetUrl, function (error, response, body) {
                    if (error) {
                        throw error;
                    }

                    res.success(JSON.parse(body).expiryTimeMillis);
                });
            });

Is this or will this get fixed?

Yes, this will get fixed in #891. In the interim, you can just assign to the credentials property as called out above.

Still broken in v24

still broken as well ...
I v tried oAuth2Client.credentials = tokens; ( which got back from oAuth2Client.getToken(code ...) )

Error msg :
{ Error: Login Required at new RequestError (C:\Users\karocksjoelee\works\growth-botic-node\node_modules\google-auth-library\lib\transporters.js:34:42) at Request._callback (C:\Users\karocksjoelee\works\growth-botic-node\node_modules\google-auth-library\lib\transporters.js:96:27) at Request.self.callback (C:\Users\karocksjoelee\works\growth-botic-node\node_modules\request\request.js:186:22) at emitTwo (events.js:126:13) at Request.emit (events.js:214:7) at Request.<anonymous> (C:\Users\karocksjoelee\works\growth-botic-node\node_modules\request\request.js:1163:10) at emitOne (events.js:116:13) at Request.emit (events.js:211:7) at IncomingMessage.<anonymous> (C:\Users\karocksjoelee\works\growth-botic-node\node_modules\request\request.js:1085:12) at Object.onceWrapper (events.js:313:30) code: 401, errors: [ { domain: 'global', reason: 'required', message: 'Login Required', locationType: 'header', location: 'Authorization' } ] }

This was fixed in the 25.0.0 release. Thanks for your patience folks!

@JustinBeckwith , the 25.0.0 release (and v26 as well) is not usable because of bug #964.
would it be possible that you fix v24 as well please?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

madc0w picture madc0w  路  3Comments

JustinBeckwith picture JustinBeckwith  路  3Comments

eduDorus picture eduDorus  路  3Comments

streamnsight picture streamnsight  路  4Comments

suparnavg picture suparnavg  路  3Comments