Google Plus Single Sign On Server Flow - Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'

最后都变了- 提交于 2019-12-04 15:56:48

It sounds like you may be sending the same authorization code multiple times. On Android GoogleAuthUtil.getToken() caches any tokens that it retrieves including authorization codes.

If you ask for a second code without invalidating the previous code, GoogleAuthUtil will return the same code. When you try to exchange a code on your server which has already been exchanged you get the invalid_grant error. My advice would be to invalidate the token immediately after you retrieve it (even if you fail to exchange the code, you are better off getting a new one than retrying with the old one).

code = GoogleAuthUtil.getToken(
    OneTimeCodeActivity.this,         // Context context
    mPlusClient.getAccountName(),     // String accountName
    scopes,                           // String scope
    appActivities                     // Bundle bundle
);

GoogleAuthUtil.invalidateToken(
    OneTimeCodeActivity.this,
    code
);

invalid_grant can be returned for other reasons, but my guess is that caching is causing your problem since you said it worked the first time.

This issue is now resolved. This was due to the implementation on the One Time Code exchange with the server

As specified in the my issue above, I used the photohunt example to do the exchange with my server. The Android code can be found on the below link

https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java

One line 44 it reads this

byte[] postBody = String.format(ACCESS_TOKEN_JSON, sAccessToken).getBytes();

This will only work if on the server side you handle the JSON. I did not.

When calling up $client->authenticate($code); in php, $code had a JSON string and therefore when calling https://accounts.google.com/o/oauth2/token the authorization code was wrong.

So it was easy as I was not sending the code in the right format.

I found this out when digging and testing https://accounts.google.com/o/oauth2/token and created a manual cURL to test the token.

As provided in the Google+ API it was stated that all examples included a One Time Code exchange, but I think the code across all platform are not consistent and one has to double check themselve to make sure everything flows correctly, which was my mistake.

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