OAuth 身份验证快速入门
对 Gemini API 进行身份验证的最简单方法是配置 API 密钥,如 Gemini API 入门指南。如果您需要更严格的访问控制,可以使用 OAuth 代替。本指南将帮助您使用 OAuth 设置身份验证。
本指南使用适合测试环境的简化身份验证方法。对于生产环境,请了解 认证和授权 之前 选择访问凭证 适合您的应用程序。
目标 #
- 为 OAuth 设置云项目
- 设置应用程序默认凭据
- 管理程序中的凭据而不是使用
gcloud auth
前提条件 #
要运行此快速入门,您需要:
设置您的云项目 #
要完成本快速入门,您首先需要设置您的云项目。
1. 启用 API #
在使用 Google API 之前,您需要在 Google Cloud 项目中将其打开。
- 在 Google Cloud 控制台中,启用 Google 生成语言 API。
2. 配置 OAuth 同意屏幕 #
接下来配置项目的 OAuth 同意屏幕并将您自己添加为测试用户。如果您已为云项目完成此步骤,请跳至下一部分。
- 在 Google Cloud 控制台中,转到 菜单 > 谷歌认证平台 > 概览.
填写项目配置表单并将用户类型设置为 外部 在 观众 部分。
填写表格的其余部分,接受用户数据政策条款,然后单击 创建.
现在,您可以跳过添加范围并单击 保存并继续。将来,当您创建在 Google Workspace 组织外部使用的应用程序时,您必须添加并验证您的应用程序所需的授权范围。
添加测试用户:
导航至 观众页面 Google Auth 平台的。
下 测试用户,点击 添加用户.
输入您的电子邮件地址和任何其他授权测试用户,然后单击 保存.
3. 授权桌面应用程序的凭据 #
要以最终用户身份进行身份验证并访问应用程序中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用程序。如果您的应用程序在多个平台上运行,则必须为每个平台创建单独的客户端 ID。
- 在 Google Cloud 控制台中,转到 菜单 > 谷歌认证平台 > 客户.
点击 创建客户端.
点击 应用类型 > 桌面应用程序.
在 名称 字段中,输入凭据的名称。该名称仅显示在 Google Cloud 控制台中。
点击 创建。将出现 OAuth 客户端创建屏幕,其中显示您的新客户端 ID 和客户端密码。
点击 OK。新创建的凭证出现在下面 OAuth 2.0 客户端 ID。
单击下载按钮保存 JSON 文件。它将被保存为
client_secret_<identifier>.json,并将其重命名为client_secret.json并将其移至您的工作目录。
设置应用程序默认凭据 #
要转换 client_secret.json 文件到可用的凭据中,将其位置传递给 gcloud auth application-default login 命令的 --client-id-file 论点。
gcloud auth application-default login \
--client-id-file=client_secret.json \
--scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'
本教程中简化的项目设置会触发 “Google 尚未验证此应用程序。” 对话框。这是正常现象,选择 “继续”.
这会将生成的 token 放置在众所周知的位置,以便可以通过 gcloud 或客户端库。
gcloud auth application-default login \
--no-browser \
--client-id-file=client_secret.json \
--scopes='https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.retriever'
设置应用程序默认凭据 (ADC) 后,大多数语言的客户端库只需很少甚至不需要帮助即可找到它们。
卷曲 #
测试其是否有效的最快方法是使用curl 来访问 REST API:
access_token=$(gcloud auth application-default print-access-token)
project_id=<MY PROJECT ID>
curl -X GET https://generativelanguage.googleapis.com/v1/models \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${access_token}" \
-H "x-goog-user-project: ${project_id}" | grep '"name"'
Python #
在 python 中,客户端库应该自动找到它们:
pip install google-genai
测试它的最小脚本可能是:
from google import genai
client = genai.Client()
print('Available base models:', [m.name for m in client.models.list()])
自行管理凭证 [Python] #
在许多情况下,您不会有 gcloud 命令可用于从客户端 ID 创建访问 token (client_secret.json)。 Google 提供了多种语言的库,让您可以在应用程序中管理该流程。本节用 python 演示了该过程。对于其他语言,此类过程的等效示例可在 驱动器 API 文档
1. 安装必要的库 #
安装适用于 Python 的 Google 客户端库和 Gemini 客户端库。
pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib
pip install google-genai
2. 编写凭证管理器 #
为了最大限度地减少单击授权屏幕的次数,请创建一个名为 load_creds.py 在您的工作目录中缓存 token.json 稍后可以重复使用的文件,或者在过期时刷新。
从以下代码开始转换 client_secret.json 文件到 token 可用于 genai.configure:
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = ['https://www.googleapis.com/auth/generative-language.retriever']
def load_creds():
"""Converts `client_secret.json` to a credential object.
This function caches the generated tokens to minimize the use of the
consent screen.
"""
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(
'client_secret.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())
return creds
3. 编写你的程序 #
现在创建您的 script.py:
import pprint
from google import genai
from load_creds import load_creds
creds = load_creds()
client = genai.Client(credentials=creds)
print()
print('Available base models:', [m.name for m in client.models.list()])
4. 运行您的程序 #
在您的工作目录中,运行示例:
python script.py
第一次运行该脚本时,它会打开一个浏览器窗口并提示您授权访问。
- 如果您尚未登录 Google 帐户,系统会提示您登录。如果您登录了多个帐户, 配置项目时请务必选择您设置为“测试帐户”的帐户。
- 授权信息存储在文件系统中,因此下次运行示例代码时,系统不会提示您授权。
您已成功设置身份验证。