Java Google Contacts API访问服务帐户认证 [英] Java Google Contacts API Access Service Account Authentication
问题描述
我尝试访问 Google联系人API ,但我的尝试失败已经获得授权。从其他(网络)语言我习惯了APIConsole和公共API密钥(授权)。
GoogleCredential凭证=新的GoogleCredential()。setAccessToken(<<<<<< PublicAPIKey>>);
System.out.println(credential.refreshToken()); // false
通过这种方式,我无法刷新令牌并且不确定如何使用公共 - accesstoken 。 ..相反,我尝试了服务帐户:
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);
尝试{
GoogleCredential凭证=新的GoogleCredential.Builder()
.setTransport(新的NetHttpTransport())
.setJsonFactory(新的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未经授权
,位于com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException .java:105)
,位于com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
位于com.google.api.client.auth.oauth2.TokenRequest .execute(TokenRequest.java:307)
,位于com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
,位于com.google.api.client .auth.oauth2.Credential.refreshToken(Credential.java:489)
at App。< init>(App.java:50)
at App.main(App.java:29)
感谢您的提示!
没有调用 setServiceAccountUser()
我的代码工作得很好。但您只需要模仿账户(service_account_mail),而不是您的个人联系人。
401 Unauthorized异常的另一个可能来源是离开 credential.refreshToken()
。
在完成的课程之下:
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
导入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.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
公共类连接器{
private static ContactsService contactService = null;
私有静态HttpTransport httpTransport;
private static final String APPLICATION_NAME =Your-App / 1.0;
private static final String SERVICE_ACCOUNT_EMAIL =xy@developer.gserviceaccount.com;
私有连接器(){
//显式私有无参数构造函数
}
public static ContactsService getInstance(){
if (contactService == null){
try {
contactService = connect();
$ b $ catch(GeneralSecurityException | IOException e){
e.printStackTrace();
}
}
return contactService;
}
private static ContactsService connect()抛出GeneralSecurityException,IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
$ b $ // @formatter:off
GoogleCredential凭证=新的GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(https://www.google.com/m8/feeds))
.setServiceAccountPrivateKeyFromP12File(new File(key.p12 ))
.build();
// @formatter:在
if(!credential.refreshToken()){
抛出新的RuntimeException(失败的OAuth刷新令牌);
}
ContactsService myService = new ContactsService(APPLICATION_NAME);
myService.setOAuth2Credentials(凭证);
返回myService;
}
}
I'm trying to access Googles Contacts API but my attempt failed already on getting authorized. From other (web) languages i'm used to the APIConsole and the public API-key (authorization).
GoogleCredential credential = new GoogleCredential().setAccessToken("<<PublicAPIKey>>");
System.out.println(credential.refreshToken()); // false
This way I'm not able to refresh the token and be unsure about using the public-key as accesstoken... Instead I tried over a 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();
}
Here my exception:
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)
Thanks for a hint!
Without calling setServiceAccountUser()
my code just worked perfectly fine. But you just will have an impersonated account (service_account_mail) not your personal contacts.
Another possible source for a "401 Unauthorized" exception is leaving the credential.refreshToken()
away. The call is necessary to write the access-code into the reference.
Below the finished class:
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.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
public class Connector {
private static ContactsService contactService = null;
private static HttpTransport httpTransport;
private static final String APPLICATION_NAME = "Your-App/1.0";
private static final String SERVICE_ACCOUNT_EMAIL = "xy@developer.gserviceaccount.com";
private Connector() {
// explicit private no-args constructor
}
public static ContactsService getInstance() {
if (contactService == null) {
try {
contactService = connect();
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
return contactService;
}
private static ContactsService connect() throws GeneralSecurityException, IOException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// @formatter:off
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JacksonFactory.getDefaultInstance())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.google.com/m8/feeds"))
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.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;
}
}
这篇关于Java Google Contacts API访问服务帐户认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!