【问题标题】:Authentication for Google Directory using API key使用 API 密钥对 Google Directory 进行身份验证
【发布时间】:2019-02-17 16:53:42
【问题描述】:

我正在尝试编写一个添加 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": "testuser@domain.com",
        "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": "testuser@domain.com",
        "changePasswordAtNextLogin": True,
        }).execute()


if __name__ == '__main__':
    main()

【问题讨论】:

    标签: oauth oauth-2.0 google-oauth google-admin-sdk google-directory-api


    【解决方案1】:

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

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

    授权 此请求需要具有以下范围的授权(阅读有关身份验证和授权的更多信息)。

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多