Error 500 backendError with Gmail API and Google A

2019-02-17 12:10发布

I'm trying to use the new Gmail API with the Google API Node client. I created a new project from the developer console, set up a new "Service Account" Client ID, and enabled access to the API.

As a proof of concept, I am simply trying to list the threads in my inbox. When I enable the OAuth 2.0 toggle for the API explorer and enter my email address, the request succeeds and I see a JSON response with data.

Now I try to do the same in Node:

var googleapis = require('googleapis');

var SERVICE_ACCOUNT_EMAIL = '...SNIP...';

// generated by: openssl pkcs12 -in ...SNIP...p12 -out key.pem -nocerts -nodes
var SERVICE_ACCOUNT_KEY_FILE = 'key.pem';
var jwt = new googleapis.auth.JWT(
        SERVICE_ACCOUNT_EMAIL,
        SERVICE_ACCOUNT_KEY_FILE,
        null,
        ['https://www.googleapis.com/auth/gmail.readonly']);

googleapis
    .discover('gmail', 'v1')
    .execute(function(err, client) {

        jwt.authorize(function(err, result) {
            if(err) console.error(err);
            else console.log(result);

            client.gmail.users.threads.list()
                .withAuthClient(jwt)
                .execute(function(err, result) {
                    if(err) console.error(err);
                    else console.log(result);
            });
        });
    });

First I print the results of the authorize() call, which looks like it returns a token, so I think I have all the OAuth stuff setup properly:

{ access_token: '...SNIP...',
  token_type: 'Bearer',
  expires_in: 1404277946,
  refresh_token: 'jwt-placeholder' }

Then I try to actually use the API, but I get an error:

{ errors: 
   [ { domain: 'global',
       reason: 'backendError',
       message: 'Backend Error' } ],
  code: 500,
  message: 'Backend Error' }

At this point, I don't know what else to try. I think the OAuth stuff is working properly, because I haven't gotten any authentication errors. I also think the API itself is working and my account is fine, because I can use it through the API Explorer. I don't see any indication that the Node library is at fault either. In short, I have no idea what the problem is. Any ideas?

1条回答
Animai°情兽
2楼-- · 2019-02-17 12:45

You are using the Service Account to authenticate your requests to GMail. Your Service Account will not have a Gmail as far as I know, only users have GMail. For this reason you will need to do the OAuth2 flow with the user (see here for example).

查看更多
登录 后发表回答