访问Google API时无效的授权

use*_*512 7 google-api google-api-java-client google-oauth

我正在尝试使用"服务帐户"授权访问来调用任何Google API.我在Google API控制台的"服务"标签中下载了".pk2"文件并激活了"URL Shortener API".每当我尝试调用任何API(URL缩短器或Adsense)时.我有以下例外 -

com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
  "error" : "invalid_grant"
}
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:303)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:323)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:345)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:526)
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:287)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:836)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
Run Code Online (Sandbox Code Playgroud)

以下是代码片段 -

    HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    JsonFactory JSON_FACTORY = new JacksonFactory();
    File privateKey = new File(ReportAdsense.class.getResource("mykey.p12").toURI());
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId("my_valid_account_id@developer.gserviceaccount.com")
            .setServiceAccountScopes(UrlshortenerScopes.URLSHORTENER)
            .setServiceAccountPrivateKeyFromP12File(privateKey)
            .build();
     Urlshortener service = new Urlshortener.Builder(new NetHttpTransport(), JSON_FACTORY, null).setHttpRequestInitializer(credential).build();
     UrlHistory history = service.url().list().execute();
Run Code Online (Sandbox Code Playgroud)

Ant*_*ton 9

首先,"服务帐户"不适用于Adsense,因为它需要用户授权.因此,对于Adsense,您应该使用Oauth 2.0.第一次使用URL授权时https://accounts.google.com/o/oauth2/token,请复制粘贴并硬编码刷新令牌.您可以使用它来获取访问令牌,指定client_id,client_secret和refresh_token以获取新的访问令牌.现在可以在您的应用程序中使用访问令牌.

关于你的错误,我遇到了类似的问题,并花了很多时间来解决它.首先,确保您使用的是有效的ServiceAccountId - 它应该指向以"developer.gserviceaccount.com"结尾的电子邮件.确保您在Google控制台API中指定了帐户范围和已激活的服务.

我通过在我的机器中同步系统时钟来解决这个问题.

有很多主题有类似的错误没有答案.更有甚者,有些人说,有时它会起作用,有时它会返回无效的补助金.它可以在一台机器上运行而在另一台机器上运行 我不知道它是否是系统时钟问题,但我会避免使用服务帐户API,因为看起来有错误和支持不会帮助你

  • "我修复了这个问题,*通过*在我的机器中同步系统时钟." 仅凭评论就让我有时间试图在针对Google Drive进行测试时弄清楚DigitalOcean虚拟机上的问题.使用http://www.rackspace.com/knowledge_center/article/using-ntp-to-sync-time中的说明更正了系统时钟,问题得以解决.谢谢!!! (4认同)