Java Google Contacts API访问服务帐户身份验证
我正在尝试访问Googles Contacts API,但在获得授权后,我的尝试已失败。从其他(web)语言到APIConsole和公共API密钥(授权),我都习惯了
GoogleCredential credential = new GoogleCredential().setAccessToken("<<PublicAPIKey>>");
System.out.println(credential.refreshToken()); // false
这样我就无法刷新令牌,也无法确定是否将公钥用作accesstoken。。。相反,我尝试了一个service account:
private static final String USER_ACCOUNT_EMAIL = "xy@gmail.com";
private static final String SERVICE_ACCOUNT_EMAIL = "xy@developer.gserviceaccount.com";
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "xy.p12";
public App() {
Set<String> scopes = new HashSet<String>();
scopes.add("https://www.google.com/m8/feeds");
try {
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(scopes)
.setServiceAccountUser(USER_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
System.out.println(credential.refreshToken());
//System.out.println(credential.getAccessToken());
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
以下是我的例外:
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 App.<init>(App.java:50)
at App.main(App.java:29)
谢谢你的提示
# 1 楼答案
没有调用
setServiceAccountUser()
我的代码运行得非常好。但你只需要一个impersonated account(服务账户\邮件)而不是你的个人联系人“401 Unauthorized”异常的另一个可能来源是离开
credential.refreshToken()
。调用是将访问代码写入引用所必需的在完成的课程下面: