2013-07-30 67 views
7

我在使用Google新的Admin SDK时遇到困难。特别是使用Oauth2的Directory API。 我觉得我快到了,但是我试图使用Directory API检索用户详细信息(我正在使用Google教育版域)。Google管理API使用Oauth2获取服务帐户(教育版) - 403错误

基本上我想要做的是编写一个python脚本,根据他们的注册状态(由我们的AD管理)来提供或取消供应用户。我有一个使用Oauth1的脚本,但想更新它以使用Oauth2。

这是根据我发现的一些例子的代码片段。

f = file('test_key.p12', 'rb') 
key = f.read() 
f.close() 
credentials = SignedJwtAssertionCredentials(
    '[email protected]', 
    key, 
    scope= 'https://www.googleapis.com/auth/admin.directory.user') 
http = httplib2.Http() 
http = credentials.authorize(http) 
service = build(serviceName='admin', version='directory_v1', http=http) 

lists = service.users().get(userKey='[email protected]').execute(http=http) 
pprint.pprint(lists) 

这段代码似乎连接正确,但是当我尝试执行查询时,出现403错误。

错误:https://www.googleapis.com/admin/directory/v1/users/[email protected]?alt=json返回 “无权访问该资源/ API”>

我的第一个想法是因为我没有在管理员控制台(Google API's console)上打开这个API,但我有。 (其实我打开了Admin SDK而不是Directory API,因为没有Directory API可以打开,看到它是Admin SDK的一部分,它可以工作?)。

是否有另一步我失踪或有我在某个地方犯了一个愚蠢的错误?

+0

你知道了吗?我想知道Directory API(也就是Admin SDK API)是否可以与服务帐户和OAuth 2.0一起使用。 (我知道其他API可以)。我明白它可以使用OAuth 1.0,但我还没有尝试过。 –

+0

@EricWalker - 是的见下面的评论。 – Bruce

回答

6

布鲁斯,

你八九不离十。使用

所以完整的代码看起来有点像这样:

# domain configuration settings 
    import domainconfig 

    f = file(domainconfig.KEY_FILE, "rb") # b reads file in binary mode; not strictly necessary, but safer to avoid strange Windows EOL characters: https://stackoverflow.com/questions/9644110/difference-between-parsing-a-text-file-in-r-and-rb-mode 
    key = f.read() 
    f.close() 

    credentials = SignedJwtAssertionCredentials(

     domainconfig.SERVICE_ACCOUNT_EMAIL, 
     key, 
     scope = domainconfig.SCOPE, 
     sub=domainconfig.SUB_ACCOUNT_EMAIL # 'sub' supercedes the deprecated 'prn' 

    ) 

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

    directoryservice = build("admin", "directory_v1", http=http) 

    users = directoryservice.users() 
    response = users.get(userKey='[email protected]').execute() 
+0

如果使用Ruby和Google的'Signet',那么当前需要对库进行一些修改来模拟具有委派角色的管理员或用户;请参阅:https://github.com/google/signet/pull/33 –

0

这应该是帮助:https://developers.google.com/drive/delegation

当断言你需要将它连接到将要改变用户的凭据。从上面的链接,请注意本节:

credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key, 
scope='https://www.googleapis.com/auth/drive', sub=user_email) 
相关问题