Chr*_* B. 5 java google-api google-api-java-client google-drive-api service-accounts
我正在用 Java 编写一个后端进程,它将模拟用户并在他们的 Google Drive 上添加/删除文档。
服务器帐户似乎已正确进行身份验证,但是当我尝试模拟用户时,我得到一个401 Unauthorized error. 请参阅下面的详细信息。
配置
我已经配置了服务器帐户如下:
我已使用管理 API 客户端访问屏幕配置域以授权 110xxxxxxxxx342 具有范围:https://www.googleapis.com/auth/drive。
Google 支持人员查看了我的配置并对其赞不绝口。
我的代码如下所示:
package com.dcm.sharingdocuments;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import com.google.api.client.auth.oauth2.TokenErrorResponse;
import com.google.api.client.auth.oauth2.TokenResponseException;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.FileList;
public class SharingDocumentsTest3 {
private static final String SERVICE_ACCOUNT_EMAIL = " anothertest@yyyyyyyyy.iam.gserviceaccount.com";
public static Drive getDriveService(String userEmail) throws Exception {
File keyFile = new File("E:\\Projects\\Workspace\\Sharing Documents\\authentication\\AnotherTestKeyFile.p12");
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE_METADATA_READONLY);
GoogleCredential credential = null;
if (userEmail == null) {
credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(keyFile).build();
credential.refreshToken();
} else {
credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL).setServiceAccountScopes(SCOPES)
.setServiceAccountPrivateKeyFromP12File(keyFile).setServiceAccountUser(userEmail).build();
credential.refreshToken();
}
Drive service = new Drive.Builder(httpTransport, jsonFactory, null).setHttpRequestInitializer(credential)
.build();
return service;
}
public static void main(String[] args) {
SharingDocumentsTest3 sdt3 = new SharingDocumentsTest3();
sdt3.execute();
}
private void execute() {
try {
Drive service = getDriveService(null);
Drive services = getDriveService("anzzzze@zzzzz.me.uk");
displayFiles(services);
} catch (Exception e) {
e.printStackTrace();
}
}
private void displayFiles(Drive service) throws Exception {
FileList result = service.files().list().setPageSize(10).execute();
List<com.google.api.services.drive.model.File> files = result.getFiles();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (com.google.api.services.drive.model.File file : files) {
Set<Entry<String, Object>> entries = file.entrySet();
Iterator<Entry<String, Object>> it = entries.iterator();
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof String) {
System.out.println("\tKey = " + key + ", Value = " + (String) value);
} else {
System.out.println("\tKey = " + key + ", Value = " + value.toString());
}
}
System.out.printf("%s (%s)\n", file.getName(), file.getId());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我按上述方式运行代码时,出现错误:
Mar 29, 2017 9:55:27 AM com.google.api.client.googleapis.services.AbstractGoogleClient <init>
WARNING: Application name is not set. Call Builder#setApplicationName.
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 com.dcm.sharingdocuments.SharingDocumentsTest3.getDriveService(SharingDocumentsTest3.java:50)
at com.dcm.sharingdocuments.SharingDocumentsTest3.execute(SharingDocumentsTest3.java:75)
at com.dcm.sharingdocuments.SharingDocumentsTest3.main(SharingDocumentsTest3.java:65)
Run Code Online (Sandbox Code Playgroud)
因此,当我设置 setServiceAccountUser 时,代码在 credential.refreshToken() 处失败。当我不这样做时,它似乎已成功刷新令牌。我尝试了这段代码的各种组合——例如注释掉 refreshToken() 行,注释掉 getDriveService(null) 行——但是每当我尝试使用/刷新为模拟用户获得的凭据时,我都会收到 401 Unauthorized 错误。
如果我修改代码,以便将 getDriveService(null) 获得的驱动器传递给 DisplayFiles(...),那么我会列出一个名为“Getting Started”的文件。因此,服务帐户授权似乎有效,Google 已将其默认文件添加到服务器帐户的云端硬盘中。
我正在使用google-*1.22.0.jar文件并Java 1.8运行上面的代码
我认为的问题在于我配置域的方式或我尝试模拟用户的方式,但我的代码看起来与网络上的许多示例一样,而且 Google 支持似乎说我已正确配置域。
您可以建议作为解决方案或下一步的任何建议将不胜感激!
我被这个问题困扰了很长时间,终于找到了我的问题。“管理 API 客户端访问”管理控制台中肯定存在错误...
您必须输入“客户端 ID”(例如 110xxxxxxxxx342)作为客户端名称,而不是“服务帐户 ID”(看起来像电子邮件的 ID)。现在,他们的文档是正确的,并且他们在文档中确实说要使用客户端 ID,我必须给他们这一点。
所以这就是错误。当我到达“管理 API”屏幕时,我看到“示例:www.example.com”。我在那里输入了服务帐户 ID,认为电子邮件地址格式比客户端 ID 更匹配“www.example.com”。我按下“授权”,条目显然已被接受,一切都很好。结果如下:
它甚至从服务 ID 生成客户端 ID!伟大的!但每次我尝试连接时,我的代码都会收到 401 错误setServiceUser()。
如果我返回到管理 API 客户端访问控制台,并且删除之前的条目并执行相同的操作,但使用客户端 ID 而不是服务 ID 除外。结果是这样的:
完全一样,但现在我没有收到 401 错误。因此,无法查看控制台并知道是否已成功配置它。我测试了3次以确保我没有失去理智......
| 归档时间: |
|
| 查看次数: |
1193 次 |
| 最近记录: |