使用user@gmail.com

时间:2016-09-15 11:39:12

标签: java service google-oauth impersonation account

我想访问一些google api服务:

  • GDrive API
  • 联系API
  • People API

我正在使用oauth2冒充服务帐户流程(您知道其中一个:Google Oauth v2 - service account description。对于模拟,您需要应用"委派域范围内的权限"谷歌应用程序控制台,下载对应的pk12文件并在谷歌控制台项目中激活api。

目前我总是得到:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at oauthsample.GDriveAPI.<init>(GDriveAPI.java:50)
at oauthsample.GDriveAPI.main(GDriveAPI.java:85)

这是我的代码:

        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();    

        Set<String> scopes = new HashSet<String>();
        scopes.add("https://www.google.com/m8/feeds");

        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId("myserviceuser@xxxxxx.iam.account.com")
                .setServiceAccountPrivateKeyFromP12File(new File("somep12key.p12"))
                .setServiceAccountScopes(scopes)
                .setServiceAccountUser("my_user_name@gmail.com")
                .build();

       credential.refreshToken();
       ContactsService service = new ContactsService("MYAPP");
        service.getRequestFactory().setHeader("User-Agent", "MYAPP");
        service.setHeader("GData-Version", "3.0");
        service.setOAuth2Credentials(credential);

        URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
        ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);

我还通过stackoverflow进行了大量搜索(无法列出所有引用并检查响应和解决方案)。但是一个问题从来没有得到明确的回答 - 谷歌文件也没有,也没有在所有的stackoverflow帖子上:

  • 是否可以使用普通的user@gmail.com用户模拟serviceaccount(我的意思是一个普通的gmail帐户,在第34章中没有访问所提到的管理控制台;委派域范围的权限到服务帐户&#34;并且没有自己的域名?)

有些人说是,有些人说不。那么绝对真理是什么?

据我所知,在阅读Google文档时:服务帐户只能在您负责自己的域时冒充用户,并且您需要拥有自己域名注册的Google工作帐户。然后,您就可以访问管理控制台,并可以授予对服务帐户的访问权限。

感谢您的耐心和时间回答。

祝你好运 马特

1 个答案:

答案 0 :(得分:4)

简短的回答是否定的,无法执行@ gmail.com帐户的服务帐户模拟。关键原因是虽然服务帐户OAuth流程不涉及授权屏幕,但在一天结束时,某人仍必须说“我授权此应用程序冒充该用户。”#34;

如果是Google Apps域,则该用户是域管理员,有权批准域中所有用户的应用。对于@ gmail.com帐户,没有其他权限可以代表您批准。如果你不得不要求用户进行授权,那么使用常规的3脚OAuth流来提示用户授权,获取刷新令牌等是有意义的。

现在有一段时间有一个技巧,你可以通过常规的3脚流程取一个@ gmail.com用户,一旦他们批准它,从那时起使用服务帐户流程。这会导致一些奇怪的问题,所以我们已经禁用了这个选项。这可能就是为什么过去存在分歧,如果可能的话。