OAuth2 “Invalid Grant” response from server

◇◆丶佛笑我妖孽 提交于 2019-12-05 01:45:01
Sourab Sharma

I got annoyed by invalid_grant error instead of the fact that same code is getting me correct access token some times.

Shaikh's answer has guided me to correct direction.

First of all we try to get access code from:

https://accounts.google.com/o/oauth2/auth

User is directed to "Allow Permission" screen and then our app receive access code.

Using that access code we try to get access token from:

https://accounts.google.com/o/oauth2/token

In the first attempt it will return us access_token with grant_type=authorization_code, but once access_token has been provided to us, it no longer expect to receive grant_type=authorization again, instead it likes to receive grant_type=refresh_token

For fellow android developers code is as follows:

String accessToken = null, refreshToken = null;
HttpPost httppost = new HttpPost(https://accounts.google.com/o/oauth2/token);
HttpParams myParams = new BasicHttpParams();
httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("client_id", BLOGGER_CLIENT_ID));
SharedPreferences prefs = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
String bloggerAccessToken = prefs.getString(PREFERENCES_KEY_BLOGGER_ACCESS_TOKEN, null);

if(bloggerAccessToken != null && bloggerAccessToken.length() > 0){
    nameValuePairs.add(new BasicNameValuePair("refresh_token",  prefs.getString(PREFERENCES_KEY_BLOGGER_REFRESH_TOKEN, null)));
    nameValuePairs.add(new BasicNameValuePair("grant_type",    "refresh_token"));
} else{
    nameValuePairs.add(new BasicNameValuePair("code",  prefs.getString(PREFERENCES_KEY_BLOGGER_ACCESS_CODE, null)));
    nameValuePairs.add(new BasicNameValuePair("grant_type",    "authorization_code"));
    nameValuePairs.add(new BasicNameValuePair("redirect_uri",  "http://localhost"));
}

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpClient = new DefaultHttpClient(myParams);
response = httpClient.execute(httppost);

String returnedJsonStr = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(returnedJsonStr);
accessToken = jsonObject.getString("access_token");
if(jsonObject.has("refresh_token"))
    refreshToken = jsonObject.getString("refresh_token");

You may ask the client to generate the code PLUS the subsequent refresh token himself. Give him the access to the form above where the refresh_token is generated.

Then you can use refresh_token to generate access_tokens.

Hope it fixes your problem.

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