使用API 密钥对Google Directory进行身份验证

问题描述 投票:1回答:1

我正在尝试编写一个可以添加G Suite帐户的脚本,但我希望在每次提交表单时都不会重定向到Google进行授权。有没有办法在脚本中进行授权?我试图授权使用API​​密钥,但获得了401 Error - Login Required

使用oAuth并重定向到Google的工作原理:

from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# If modifying these scopes, delete the file token.json.
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'

def main():



    store = file.Storage('token.json')
    creds = store.get()

    if not creds or creds.invalid:
            flow = client.flow_from_clientsecrets('creds.json', SCOPES)
            creds = tools.run_flow(flow, store)

    service = build('admin', 'directory_v1', http=creds.authorize(Http()))


    print('Adding user...')
    #create a user
    service.users().insert(body={
        "name": {
            "givenName": "John",
            "fullName": "John Smith",
            "familyName": "Smith",
            },
        "password": "password",
        "primaryEmail": "[email protected]",
        "changePasswordAtNextLogin": True,
        }).execute()


if __name__ == '__main__':
    main()

使用我的API密钥返回401 Error

API_KEY = 'key'
def main():

    service = build('admin', 'directory_v1', developerKey=API_KEY)


    print('Adding user...')
    #create a user
    service.users().insert(body={
        "name": {
            "givenName": "John",
            "fullName": "John Smith",
            "familyName": "Smith",
            },
        "password": "password",
        "primaryEmail": "[email protected]",
        "changePasswordAtNextLogin": True,
        }).execute()


if __name__ == '__main__':
    main()
oauth oauth-2.0 google-oauth google-admin-sdk google-directory-api
1个回答
1
投票

您需要了解的第一件事是私有数据和公共数据之间的区别。私有数据是用户拥有的数据,并且要求您具有用户访问权限。公共数据不属于任何人。您可以使用api密钥访问公共数据,但不能访问私有数据。

如果你检查Users: insert你会注意到它的状态。

授权此请求需要具有以下范围的授权(有关身份验证和授权的详细信息,请参阅)。

范围https://www.googleapis.com/auth/admin.directory.user

所以这是一种需要身份验证的方法。您有两个选项Oauth2并请求用户访问或使用服务帐户。服务帐户就像一个虚拟用户,这个虚拟用户通过domain wide delication被授予访问权限,它通常用于服务器到服务器通信,其中没有用户对代码进行身份验证。我建议你考虑设置它。

© www.soinside.com 2019 - 2024. All rights reserved.