每当尝试从服务帐户获取访问令牌时都会出现错误 [英] Got error whenever trying to get access token from service account
问题描述
INFO:com.google.api.client.auth.oauth2.TokenResponseException:400 OK
{
error:invalid_grant
}
我的代码是
GoogleCredential凭证=新的GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(js)
.setServiceAccountId(emailId)
.setServiceAccountScopes(
.setServiceAccountPrivateKeyFromP12File(new File(privateKeyPath))。build();
System.out.println(SERVICE ACCOUNT SERVLET CALLED);
credential.refreshToken();
这种方法运行良好,但突然开始出错。
1)我的服务器上有类似的问题不正确。确保你的系统时钟是同步的。
2)您应该重用第一次成功验证后获得的访问令牌。如果您的上一个令牌尚未过期,您将收到invalid_grant错误。 3)确保你传递了访问令牌,而不是刷新令牌,因为它失败了。运行时,会将OAUth2刷新令牌变为访问令牌并将其传递给服务。如果您传递了原始刷新标记,则API访问不接受此标记,而不将其转换为短期访问标记。
4)您可能已达到刷新令牌限制。某些Google API具有此功能,您可以在这里找到一些说明: https://developers.google.com/计算/文档/认证
5)您也可以撤消它。转到您的Google API控制台( https://code.google.com/apis/console/),并在客户端ID下为已安装的应用程序撤消您的客户端密码。请务必使用新的客户端密码更新您的代码
INFO: com.google.api.client.auth.oauth2.TokenResponseException: 400 OK
{
"error" : "invalid_grant"
}
my code is
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(js)
.setServiceAccountId(emailId)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(new File(privateKeyPath)).build();
System.out.println("SERVICE ACCOUNT SERVLET CALLED");
credential.refreshToken();
this method is running fine but suddenly it starts to give error.
Possible reasons:
1) I was having a similar problem caused by the time on my server being incorrect. Make sure your system clock is synchronized.
2) You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it.
3) Make sure that you pass the access token, and not refresh token as that fails. When you run, it turns the OAUth2 refresh token into an access token and passes that to the service. If you pass the raw refresh token, this is not acceptable for API access without turning it into a short-lived access token.
4) You might have reached the refresh token limit. Certain Google APIs have this, some explanation you can find here: https://developers.google.com/compute/docs/authentication
5) You also can revoke it. Go to your Google API Console ( https://code.google.com/apis/console/ ) and revoke your Client Secret under Client ID for installed applications. Be sure to also update your code with the new Client Secret
这篇关于每当尝试从服务帐户获取访问令牌时都会出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!