【问题标题】:Authorize google api requests to list users授权 google api 请求列出用户
【发布时间】:2021-11-19 21:01:40
【问题描述】:

我想获取 google api 用户列表,但遇到问题 我的步骤是:

  1. 已创建具有域范围委派和列出范围的服务帐户(与脚本中相同)
  2. 已下载带有私钥的 json 文件

在执行下一个脚本时

import google.auth
import google.auth.transport.requests
from google.oauth2 import service_account
import requests

credentials = service_account.Credentials.from_service_account_file('key.json', scopes=[
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.group',
    'https://www.googleapis.com/auth/admin.directory.group.member',
    'https://www.googleapis.com/auth/admin.directory.user.security',
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
])
auth_req = google.auth.transport.requests.Request()
refresh = credentials.refresh(auth_req)
response = requests.get('https://www.googleapis.com/admin/directory/v1/users?domain=domain.com',
                    headers={'Authorization': f'Bearer {credentials.token}'})

回复是:

{
   "error": {
      "code": 403,
      "message": "Not Authorized to access this resource/api",
      "errors": [
         {
            "message": "Not Authorized to access this resource/api",
            "domain": "global",
            "reason": "forbidden"
         }
      ]
   }
}

【问题讨论】:

    标签: python google-api


    【解决方案1】:

    我最终得到了下一个解决方案

    1. console.cloud.google.com => API 和服务 > 凭据
    2. 创建凭据 > OAuth 客户端 ID > 桌面应用程序
    3. 将密钥保存为“credentials.json”

    这里描述的其余id

    from __future__ import print_function
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
    
    #
    
    def main():
        """Shows basic usage of the Admin SDK Directory API.
        Prints the emails and names of the first 10 users in the domain.
        """
        creds = None
        # The file token.json 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.json'):
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        # 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:
                print('Refreshing token')
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'python_admin.json', SCOPES)
                creds = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open('token.json', 'w') as token:
                token.write(creds.to_json())
    
        service = build('admin', 'directory_v1', credentials=creds)
    
        # Call the Admin SDK Directory API
        print('Getting the first 10 users in the domain')
        service_users = service.users()
        results = service_users.list(customer='my_customer', maxResults=10, orderBy='email').execute()
        users = results.get('users', [])
    
        service_users.insert()
    
        if not users:
            print('No users in the domain.')
        else:
            print('Users:')
            for user in users:
                print(u'{0} ({1})'.format(user['primaryEmail'],
                    user['name']['fullName']))
    
    
    if __name__ == '__main__':
        main()
    

    我第一次必须在浏览器中授权请求,之后访问和刷新令牌可以用于下一个请求。除了第一次手动授权 - 工作正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-27
      • 2015-10-15
      • 2017-09-24
      • 2014-11-06
      • 1970-01-01
      • 2021-05-24
      • 2017-02-22
      • 1970-01-01
      相关资源
      最近更新 更多