尝试从服务帐户获取访问令牌时出错 [英] Got error whenever trying to get access token from service account

查看:31
本文介绍了尝试从服务帐户获取访问令牌时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

INFO: com.google.api.client.auth.oauth2.TokenResponseException: 400 OK
{
  "error" : "invalid_grant"
}

我的代码是

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.

推荐答案

可能的原因:

1) 由于我的服务器上的时间不正确,我遇到了类似的问题.确保您的系统时钟同步.

1) I was having a similar problem caused by the time on my server being incorrect. Make sure your system clock is synchronized.

2) 您应该重复使用在第一次成功认证后获得的访问令牌.如果您之前的令牌尚未过期,您将收到 invalid_grant 错误.将其缓存在某处,以便您可以重复使用.

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) 确保您传递访问令牌,而不是刷新令牌,因为它失败了.当您运行时,它会将 OAUth2 刷新令牌转换为访问令牌并将其传递给服务.如果您传递原始刷新令牌,这对于 API 访问来说是不可接受的,而不会将其转换为短期访问令牌.

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) 您可能已达到刷新令牌限制.某些 Google API 具有此功能,您可以在此处找到一些解释:https://developers.google.com/计算/文档/身份验证

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) 您也可以撤销它.转到您的 Google API 控制台 ( https://code.google.com/apis/console/ ) 并在已安装的应用程序的客户端 ID 下撤销您的客户端密钥.请务必同时使用新的客户端密钥更新您的代码

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆