Google Analytics API oauth exception “invalid_grant” with Service Account. Same code on two servers. Only one works

孤街浪徒 提交于 2019-11-29 04:08:34

Apparently the problem was the system time being off. Worked by sync-ing via NTP with:

sudo ntpdate npt.ubuntu.com

sudo ntpdate pool.ntp.org

Edit

As @RafaSashi suggested below, the pool.ntp.org server is more reliable. Use that instead of ntp.ubuntu.com (which was the first working one I tried, thus the initial choice).

The invalid grant can also be caused if you use the wrong "ServiceAccountId". It should be the email associated with the client id in the service account client id in the google apis access page. You'd also have to add this user to the google analytics account that you're planning to access.

This tripped me up because I assumed the email address they were referring to was the email address of my google account, since I used the same google account to get api access as I do for google analytics. I know Vir's already figured his out, just thought I'd add this in case someone else comes across the same question and, like me, their computer seems to be in sync with NTP.

In addition to Valer's answer:

First, you’ll need to install NTP if it isn’t already installed. For Debian or Ubuntu, that would be this command:

sudo apt-get install ntp

For Redhat or CentOS, you’ll need to use this one:

yum install ntp

If the synchronization via npt.ubuntu.com doesn't work try :

sudo ntpdate pool.ntp.org

Resources

There are two major reasons for invalid_grant error which you have to take care prior to the POST request for Refresh Token and Access Token.

  1. Request header must contain "content-type: application/x-www-form-urlencoded"
  2. Your request payload should be url encoded Form Data, don't send as json object.

RFC 6749 OAuth 2.0 defined invalid_grant as: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

I found another good article, here you will find many other reasons for this error.

https://blog.timekit.io/google-oauth-invalid-grant-nightmare-and-how-to-fix-it-9f4efaf1da35

Google Playground is best tool which help you how to send request. https://developers.google.com/oauthplayground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!