2013-11-26 159 views
0

我正在使用服务帐户通过管理目录和Google+域API成功模拟管理员用户,但我无法弄清楚网站是否可以使用服务帐户。它甚至有可能吗?我指的是允许您创建和删除网站的API,而不是用于管理内容的网站管理员工具API等。可能在Sites API中使用Google服务帐户

回答

0

是的,它是可能的。下面是一个代码示例:

SitesService sitesService = new SitesService("MyApplication"); 
final GoogleCredential credential = new GoogleCredential.Builder() 
       .setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()) 
       .setServiceAccountId("XXXX.apps.googleusercontent.com") 
       .setServiceAccountScopes(Collections.singleton(SERVICE_SCOPES)) 
       .setServiceAccountPrivateKeyFromP12File(new File("key.p12")) 
       .setServiceAccountUser("[email protected]").build(); 
sitesService.setOAuth2Credentials(credential); 

你必须与谨慎的唯一的事情,就是一些SitesService方法可能无法正确地刷新令牌,在这种情况下,你将不得不赶上SessionExpiredException并刷新Credential你自己。

0

Google Sites API网页上说[1]您可以使用它创建新网站或复制现有网站。

[1] https://developers.google.com/google-apps/sites

+0

是的,我已经使用该API创建站点(使用Java版本),但我使用用户/传球组合登录,并且我想使用服务帐户模仿用户,因为我正在使用Directory ,Google +或Google日历API。 – momo

1

您可以使用网站的API服务帐户。您只需使用SignedJwtAssertionCredentials,从后台模拟用户并访问GData API。

这里是代码片段:

credentials = SignedJwtAssertionCredentials(
     SERVICE_ACCOUNT_EMAIL, 
     file(SERVICE_ACCOUNT_PEM_FILE_PATH, "rb").read(), 
     scope=["https://sites.google.com/feeds/"], 
     prn=userEmailYouWantToImpersonate 
    ) 

http = httplib2.Http() 
http = credentials.authorize(http) 

sitesClient = gdata.sites.client.SitesClient(source='mycompany', site='mySite', domain='mydomain') 
sitesClient.auth_token = TokenFromOAuth2Creds(credentials) 
feed = sitesClient.GetContentFeed() 

class TokenFromOAuth2Creds: 
    def __init__(self, creds): 
     self.creds = creds 
    def modify_request(self, req): 
     if self.creds.access_token_expired or not self.creds.access_token: 
      self.creds.refresh(httplib2.Http()) 
     self.creds.apply(req.headers) 
相关问题