Python / GCP - GitHub 操作 & Google OAuth 无需提交 ID

发布于 2025-01-20 10:34:30 字数 1754 浏览 4 评论 0原文

对于使用YouTube API的项目,我正在使用一个函数,该函数从JSON文件中读取我的OAuth 2.0 ID,自动创建 /刷新凭据,然后生成服务以执行所有类型的API请求。我已经在本地运行了几天,没有任何问题。但是现在,我想使用GitHub动作和特定触发器自动化项目。

我的功能看起来大致是这样:

import ast
import googleapiclient.discovery
import googleapiclient.errors
import json
import os
import sys

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

def get_authenticated_service():
    # OAUTH 2.0 ID path
    oauth_file = '../tokens/oauth.json'
    scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
    cred = None

    if os.path.exists('../tokens/credentials.json'):
        # Retrieve credentials
        cred = Credentials.from_authorized_user_file('../tokens/credentials.json')

    if not cred or not cred.valid:  # Cover outdated credentials
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())

        else:
            # Create a Flow from 'oauth_file'
            flow = InstalledAppFlow.from_client_secrets_file(oauth_file, scopes)
            # Run authentification process
            cred = flow.run_local_server()

        with open('../tokens/credentials.json', 'w') as cred_file:
            # Save credentials as a JSON file
            json.dump(ast.literal_eval(cred.to_json()), cred_file, ensure_ascii=False, indent=4)

    try:
        service = googleapiclient.discovery.build('youtube', 'v3', credentials=cred)
        return service

    except Exception as error:
        sys.exit()

问题是我与公共存储库共享我的代码,而我不想共享 /提交我的ID(令牌中的内容< / code>文件夹中的内容)。我刚刚开始学习GitHub Action的工作原理,我不知道如何将我当前的方法转换为可能在工作流程中完成工作的事物。这甚至可能吗?

For a project using the YouTube API, I am using a function that reads my OAuth 2.0 ID from a JSON file, creates / refreshes the credentials automatically and then generate a service to perform all kind of API requests. I've been running the script locally for a few days now, without any problems. But now I would like to automate my project using GitHub Action and specific triggers.

My function looks roughly like this:

import ast
import googleapiclient.discovery
import googleapiclient.errors
import json
import os
import sys

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

def get_authenticated_service():
    # OAUTH 2.0 ID path
    oauth_file = '../tokens/oauth.json'
    scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
    cred = None

    if os.path.exists('../tokens/credentials.json'):
        # Retrieve credentials
        cred = Credentials.from_authorized_user_file('../tokens/credentials.json')

    if not cred or not cred.valid:  # Cover outdated credentials
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())

        else:
            # Create a Flow from 'oauth_file'
            flow = InstalledAppFlow.from_client_secrets_file(oauth_file, scopes)
            # Run authentification process
            cred = flow.run_local_server()

        with open('../tokens/credentials.json', 'w') as cred_file:
            # Save credentials as a JSON file
            json.dump(ast.literal_eval(cred.to_json()), cred_file, ensure_ascii=False, indent=4)

    try:
        service = googleapiclient.discovery.build('youtube', 'v3', credentials=cred)
        return service

    except Exception as error:
        sys.exit()

The problem is that I share my code with a public repository and I don't want to share / commit my ID (what is in token folder). I'm just starting to learn how GitHub Action works and I have no idea of how to transpose my current method to something that might do the job in a workflow. Is this even possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素手挽清风 2025-01-27 10:34:30

遵循@dazwilkin的答案,我找到了一种使用Google API Python客户端使用Workflow Identity Federation Federation的方法。我花了一段时间才弄清楚所有这些工作是如何工作的,但是现在我可以提供答案。和“令人惊讶的是”,设置非常简单。

在设置联邦后a>,您可以在所需的工作流(YAML文件)中添加这些身份验证行:

steps:
    -   id: checkout
        name: Checkout repository
        uses: actions/checkout@v3
    
    -   id: auth
        name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v0
        with:
            token_format: 'access_token'
            access_token_scopes: 'https://www.googleapis.com/auth/youtube.force-ssl'
            workload_identity_provider: 'projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider'
            service_account: '[email protected]'
        
# TODO: Install dependencies, program execution...

然后使用google.auth的默认方法来完成使用Python客户端的服务创建:

import google.auth
import googleapiclient.discovery

def create_service_workflow():
    scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
    credentials, _ = google.auth.default(scopes=scopes)
    service = googleapiclient.discovery.build('youtube', 'v3', credentials=credentials)
    return service

Following @DazWilkin's answer, I found a way to use the Google API Python Client using a Workflow Identity Federation. It took me a while to figure out how all of this is working, but now I can provide an answer. And "surprisingly", it's quite simple to set up.

After setting-up your Federation, you can add these authentication lines in the desired workflow (YAML file):

steps:
    -   id: checkout
        name: Checkout repository
        uses: actions/checkout@v3
    
    -   id: auth
        name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v0
        with:
            token_format: 'access_token'
            access_token_scopes: 'https://www.googleapis.com/auth/youtube.force-ssl'
            workload_identity_provider: 'projects/123456789/locations/global/workloadIdentityPools/my-pool/providers/my-provider'
            service_account: '[email protected]'
        
# TODO: Install dependencies, program execution...

The service's creation with the Python client is then done with the google.auth's default method:

import google.auth
import googleapiclient.discovery

def create_service_workflow():
    scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
    credentials, _ = google.auth.default(scopes=scopes)
    service = googleapiclient.discovery.build('youtube', 'v3', credentials=credentials)
    return service
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文