在oAuth Google Api Flow…gDrive中使用“ create_delegated”存在问题

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

问题的重点是在运行以下内容时,我无法将凭据委派给其他用户帐户。唯一的在线示例使用的是JSON服务帐户,而不是oAuth身份验证流程。

newcreds = creds.create_delegated('[email protected]')
AttributeError: 'Credentials' object has no attribute 'create_delegated'

我的代码突出显示在下面,正常的凭据登录可正常运行,但需要访问其他用户帐户.....

#!/usr/bin/env python
from __future__ import print_function
import pickle
import os.path
import json
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

import sys

print('test')
##VARS
SCOPES = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/admin.directory.user']
creds = None
count = 0
##Google Creds
creds = None
if os.path.exists(os.path.dirname(os.path.abspath(__file__))+'/secrets/token.pickle'):
    with open(os.path.dirname(os.path.abspath(__file__))+'/secrets/token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            os.path.dirname(os.path.abspath(__file__))+'/secrets/credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open(os.path.dirname(os.path.abspath(__file__))+'/secrets/token.pickle', 'wb') as token:
        pickle.dump(creds, token)

newcreds = creds.create_delegated('[email protected]')

service = build('drive', 'v3', credentials=creds)

api google-api google-drive-api
1个回答
1
投票

使用Google-OAuth 2.0管理用户

管理GSuite域用户必须分为两部分

  1. Admin SDK方法,例如创建用户,检索用户,更新用户等(基本上,管理员可以在admin console中执行的所有操作)都可以通过域管理员直接使用其凭据进行身份验证来访问]]
  2. 涉及使用大多数其他API(驱动器API,Gmail API等)和访问私人用户数据的方法不是GSuite管理员可以直接访问的。
  3. 出于安全原因,后者必须通过service account执行。

  • [创建(或更新)服务帐户时,管理员可以决定授予哪个范围并执行domain-wide delegation
  • 域范围内的委派意味着impersonating允许该服务帐户代表域用户-该用户充当用户,并且对用户数据的访问与用户本人几乎相同。
  • 用于服务帐户的身份验证流程与常见的Google API身份验证不同。
  • 没有以相同方式创建的访问或刷新令牌,并且在管理员的工作目录中没有存储任何token.json文件。
  • 相反,在GCP控制台中创建服务帐户时,需要将服务帐户凭据作为jsonp12文件下载到工作目录。
  • [用于在Python中使用具有json凭据文件的模拟服务帐户定义:
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('[email protected]')
drive_service = googleapiclient.discovery.build(
        'drive', 'v3', credentials=delegated_credentials)

[with_subject是使服务模仿用户的关键部分。

所示的范围必须与您在管理控制台中分配给服务帐户的范围相匹配。

使用服务帐户时,删除用于常规身份验证的代码部分,即

    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

其他信息

如果您更喜欢使用p12凭据文件而不是json,则with_subject将通过create_delegated替换。

示例:

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# Email of the Service Account
SERVICE_ACCOUNT_EMAIL = 'YOUR SERVICE ACCOUNT EMAIL'

# Path to the Service Account's Private Key file
SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12'

def create_directory_service(user_email):
    """Build and returns an Admin SDK Directory service object authorized with the service accounts
    that act on behalf of the given user.

    Args:
      user_email: The email of the user. Needs permissions to access the Admin APIs.
    Returns:
      Admin SDK directory service object.
    """

    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_EMAIL,
        SERVICE_ACCOUNT_PKCS12_FILE_PATH,
        'notasecret',
        scopes=['https://www.googleapis.com/auth/drive'])

    credentials = credentials.create_delegated(user_email)

    return build('drive', 'v3', credentials=credentials)
© www.soinside.com 2019 - 2024. All rights reserved.