服務帳戶,我想訪問一些谷歌的API服務:谷歌的oauth2模仿與[email protected]
- GDrive的API
- 聯繫API
- 人民API
而且我使用oauth2模擬服務帳戶流程(您知道一個:Google Oauth v2 - service account description。對於模仿,您需要在Google應用程序控制臺中應用「委託域範圍的權限」,請下載t他相應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("[email protected]")
.setServiceAccountPrivateKeyFromP12File(new File("somep12key.p12"))
.setServiceAccountScopes(scopes)
.setServiceAccountUser("[email protected]")
.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);
我也搜索過重計算器(不能列出所有引用,並檢查了應對措施和解決) 。但是,有一個問題一直沒有明確答覆 - 也沒有在谷歌documentaiont也不是對所有的計算器帖子:
- 是否真的能夠模仿與正常[email protected]用戶serviceaccount(我指的是正常的Gmail帳戶沒有訪問提到的管理控制檯的章節「委託域服務帳戶的權限」和沒有自己的域)?
有的說是,有的說不。那麼,絕對的真相是什麼?
據我瞭解當閱讀谷歌文檔時:服務帳戶只能模擬用戶當你負責自己的域名,你需要有一個谷歌工作帳戶與自己的域名註冊。然後,您可以訪問管理控制檯並授予對該服務帳戶的訪問權限。
感謝您的耐心等待和時間回答。
問候 馬特
是否真的有可能模仿serviceaccount。懷疑它可能回來了,當我們有客戶端登錄。我從來沒有與Oauth合作過。令我印象深刻的是,您可以混合發現apis和gdata apis,這不容易:) – DaImTo
作爲進一步的輸入,我只能說上面的代碼是大量嘗試錯誤和stackoverflow解決方案的混合體。我的代碼中斷位於「credential.refreshToken();」行所以我想我無法獲得授權的新令牌。是的,你是對的,它是gdata和發現apis的混合物..但這不是重點。除非您擁有正確且正在運行的oauth憑證設置,否則您可以將所需的任何服務(People API,Gdrive API,...) – samatthias
你不應該需要這個服務帳戶。注意:我不是一個java程序員。 – DaImTo