簡體   English   中英

為 Google Drive API 創建 Google Credentials 對象而不從文件加載

[英]Creating Google Credentials object for Google Drive API without loading from file

我正在嘗試創建一個谷歌憑據對象來訪問谷歌驅動器。 我將令牌和用戶數據存儲在會話中,因此我嘗試創建對象而不從 credentials.json 文件加載它們。 當用戶首次登錄 Web 應用程序並將令牌存儲在用戶會話中時,我正在處理身份驗證,會話的超時時間與默認訪問令牌相同,因此 24 小時后用戶被要求再次登錄因此創建了一個具有有效訪問令牌的新會話。 所以我的想法是重用訪問令牌來限制登錄次數並改善用戶體驗。

這是關於我如何嘗試創建 google 憑據對象的一小段代碼

from oauth2client.client import GoogleCredentials

access_token = request.session['access_token']
gCreds = GoogleCredentials( 
         access_token, 
         os.getenv('GOOGLE_CLIENT_ID'),
         os.getenv('GOOGLE_CLIENT_SECRET'), 
         refresh_token=None, 
         token_expiry=None,
         token_uri=GOOGLE_TOKEN_URI, 
         user_agent='Python client library',
         revoke_uri=None)
build('drive', 'v3', credentials = gCred)


每當我嘗試運行此代碼時,都會出現以下錯誤:


Insufficient Permission: Request had insufficient authentication scopes.". Details: "[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request had insufficient authentication scopes.'}]"

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

那么什么是作用域。 范圍定義您向用戶請求的訪問權限。 在這種情況下,您想訪問他們的 Google 雲端硬盤帳戶,但您需要多少訪問權限取決於您將使用的方法。

如果你只是使用 file.list 那么你可以請求一個只讀范圍,因為你不會寫任何東西。

https://www.googleapis.com/auth/drive.readonly

但是,如果您要很好地使用 file.create,您將需要一個寫入范圍。 您需要獲得寫入他們 Google 帳戶的權限

https://www.googleapis.com/auth/drive

我無法從您的代碼中看到您是如何處理授權的。 因此,讓我們從查看官方的google drive python 示例開始

在下面的代碼中注意他們是如何調用的

InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)

並定義他們想要請求的訪問范圍。

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    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:
            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.json', 'w') as token:
            token.write(creds.to_json())

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

        # Call the Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('No files found.')
            return
        print('Files:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

錯誤信息

錯誤信息

請求的身份驗證范圍不足。”。詳細信息:“[{'domain': 'global', 'reason': 'insufficientPermissions', 'message': 'Insufficient Permission: Request has enough authentication scopes.'}]">成功連接駕車

實際上意味着您已經向用戶請求了一個范圍,可以說是只讀的,但您正試圖將它與需要寫訪問權限的方法一起使用。 所以你的請求沒有足夠的身份驗證范圍。

修復您的代碼以請求正確的范圍刪除您現在擁有的刷新令牌並再次請求具有正確范圍的用戶授權。

對象已正確構建,以這種方式構建對象沒有問題

access_token = request.session['access_token']
gCreds = GoogleCredentials( 
         access_token, 
         os.getenv('GOOGLE_CLIENT_ID'),
         os.getenv('GOOGLE_CLIENT_SECRET'), 
         refresh_token=None, 
         token_expiry=None,
         token_uri=GOOGLE_TOKEN_URI, 
         user_agent='Python client library',
         revoke_uri=None)
build('drive', 'v3', credentials = gCred)

該問題是在注冊范圍時在較早階段引起的

oauth = OAuth(config)
oauth.register(
    name='google',
    server_metadata_url='',
    client_kwargs={
        'scope': 'openid email profile https://www.googleapis.com/auth/drive.readonly'
    }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM