我在使用 OAuth 2.0 通过 Java 连接到 Google Contacts API 时遇到问题。经过广泛的搜索,我已经达到了可以连接的地步,但在最终过程中收到错误消息。
我做了以下事情:
1) 通过 Google 的开发者控制台为该项目创建了一个 OAuth 2.0 服务帐户。
2) 按照我在https://developers.google.com/identity/protocols/OAuth2ServiceAccount找到的“将域范围的权限委派给服务帐户”的步骤,我已授权在步骤 # 中创建的服务帐户的客户端 ID 1 到范围https://www.google.com/m8/feeds/的联系人(读/写)。
3)这是我基于其他成员帖子的代码:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.gdata.client.contacts.ContactsService;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
public class Connector {
private static ContactsService contactService = null;
private static HttpTransport httpTransport;
private static final String APPLICATION_NAME = "MyProject";
private static final String SERVICE_ACCOUNT_EMAIL = "service-account-email-address@developer.gserviceaccount.com";
private static final java.util.List<String> SCOPE = Arrays.asList("https://www.google.com/m8/feeds");
private Connector() {
// explicit private no-args constructor
}
public static ContactsService getInstance() {
if (contactService == null) {
try {
contactService = connect();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return contactService;
}
private static ContactsService connect() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
java.io.File p12File = new java.io.File("MyProject.p12");
// @formatter:off
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPE)
.setServiceAccountPrivateKeyFromP12File(p12File)
.setServiceAccountUser("user@example.com")
.build();
// @formatter:on
if (!credential.refreshToken()) {
throw new RuntimeException("Failed OAuth to refresh the token");
}
ContactsService myService = new ContactsService(APPLICATION_NAME);
myService.setOAuth2Credentials(credential);
return myService;
}
}
从理论上讲,我相信这应该是可行的。但是,当credential.refreshToken()执行时,我收到错误:
com.google.api.client.auth.oauth2.TokenResponseException: 403 Forbidden
{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}
如果我删除setServiceAccountUser("user@example.com"),我会收到错误消息com.google.gdata.util.ServiceForbiddenException: Cannot request Contacts belongs to another user。我相信我需要保留 setServiceAccountUser(...) 但无法通过令牌响应异常。
我不确定从这里去哪里。
感谢您提供的任何建议或帮助。