quickstarts/Authentication_with_OAuth.ipynb (467 lines of code) (raw):

{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "Tce3stUlHN0L" }, "source": [ "##### Copyright 2025 Google LLC." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "tuOe1ymfHZPu" }, "outputs": [], "source": [ "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n", "# you may not use this file except in compliance with the License.\n", "# You may obtain a copy of the License at\n", "#\n", "# https://www.apache.org/licenses/LICENSE-2.0\n", "#\n", "# Unless required by applicable law or agreed to in writing, software\n", "# distributed under the License is distributed on an \"AS IS\" BASIS,\n", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", "# See the License for the specific language governing permissions and\n", "# limitations under the License." ] }, { "cell_type": "markdown", "metadata": { "id": "yeadDkMiISin" }, "source": [ "# Gemini API: OAuth Quickstart" ] }, { "cell_type": "markdown", "metadata": { "id": "lEXQ3OwKIa-O" }, "source": [ "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Authentication_with_OAuth.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>" ] }, { "cell_type": "markdown", "metadata": { "id": "df1767a3d1cc" }, "source": [ "Some parts of the Gemini API like model tuning and semantic retrieval use OAuth for authentication.\n", "\n", "If you are a beginner, you should start by using [API keys](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb), and come back to this OAuth guide only when you need it for these features.\n", "\n", "To help you get started with OAuth, this notebook shows a simplified approach that is appropriate\n", "for a testing environment.\n", "\n", "For a production environment, learn\n", "about [authentication and authorization](https://developers.google.com/workspace/guides/auth-overview) before [choosing the access credentials](https://developers.google.com/workspace/guides/create-credentials#choose_the_access_credential_that_is_right_for_you) that are appropriate for your app." ] }, { "cell_type": "markdown", "metadata": { "id": "GUZ1vR5VHhkH" }, "source": [ "## Prerequisites\n", "\n", "To run this quickstart, you need:\n", "\n", "* The [Google Cloud CLI](https://cloud.google.com/sdk/docs/install-sdk) installed on your local machine.\n", "* [A Google Cloud project](https://developers.google.com/workspace/guides/create-project).\n", "\n", "If you created an API key in Google AI Studio, a Google Cloud project was made for you. Go to [Google AI Studio](https://aistudio.google.com/app/apikey) and note the Google Cloud project name to use that project." ] }, { "cell_type": "markdown", "metadata": { "id": "6F4DgkaWH8HW" }, "source": [ "## Set up your Cloud project\n", "\n", "To complete this quickstart, you first need to setup your Cloud project.\n", "\n", "### 1. Enable the API\n", "\n", "Before using Google APIs, you need to turn them on in a Google Cloud project.\n", "\n", "* In the Google Cloud console, [enable](https://console.cloud.google.com/flows/enableapi?apiid=generativelanguage.googleapis.com) the Google Generative Language API. If you created an API Key in AI Studio, this was done for you.<br>\n", "\n", "### 2. Configure the OAuth consent screen\n", "\n", "Next configure the project's OAuth consent screen and add yourself as a test user. If you've already completed this step for your Cloud project, skip to the next section.\n", "\n", "1. In the Google Cloud console, go to the [OAuth consent screen](https://console.cloud.google.com/apis/credentials/consent), this can be found under **Menu** > **APIs & Services** > **OAuth\n", " consent screen**.\n", "\n", "2. Select the user type **External** for your app, then click **Create**.\n", "\n", "3. Complete the app registration form (you can leave most fields blank), then click **Save and Continue**.\n", "\n", "4. For now, you can skip adding scopes and click **Save and Continue**. In the\n", " future, when you create an app for use outside of your Google Workspace\n", " organization, you must add and verify the authorization scopes that your\n", " app requires.\n", "\n", "5. Add test users:\n", " 1. Under **Test users**, click **Add users**.\n", " 2. Enter your email address and any other authorized test users, then\n", " click **Save and Continue**.\n", "\n", "6. Review your app registration summary. To make changes, click **Edit**. If\n", " the app registration looks OK, click **Back to Dashboard**.\n", "\n", "### 3. Authorize credentials for a desktop application\n", "\n", "To authenticate as an end user and access user data in your app, you need to\n", "create one or more OAuth 2.0 Client IDs. A client ID is used to identify a\n", "single app to Google's OAuth servers. If your app runs on multiple platforms,\n", "you must create a separate client ID for each platform.\n", "\n", "1. In the Google Cloud console, go to [Credentials](https://console.cloud.google.com/apis/credentials/consent), this can be found under **Menu** > **APIs & Services** >\n", " **Credentials**.\n", "\n", "2. Click **Create Credentials** > **OAuth client ID**.\n", "3. Click **Application type** > **Desktop app**.\n", "4. In the **Name** field, type a name for the credential. This name is only\n", " shown in the Google Cloud console.\n", "5. Click **Create**. The OAuth client created screen appears, showing your new\n", " Client ID and Client secret.\n", "6. Click **OK**. The newly created credential appears under **OAuth 2.0 Client\n", " IDs.**\n", "7. Click the download button to save the JSON file. It will be saved as\n", " `client_secret_<identifier>.json`.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "kfSJNy1sS9NO" }, "source": [ "## Set up application default credentials\n", "\n", "In this quickstart you will use [application default credentials](https://cloud.google.com/docs/authentication/application-default-credentials) to authenticate." ] }, { "cell_type": "markdown", "metadata": { "id": "dEoigYI9Jw_K" }, "source": [ "### Add client secret to Colab secrets\n", "\n", "If you need to use OAuth with the Gemini API in Google Colab frequently, it is easiest to add the contents of your `client_secret.json` file into Colab's Secrets manager.\n", "\n", "1. Open your Google Colab notebook and click on the 🔑 **Secrets** tab in the left panel.\n", "2. Create a new secret with the name `CLIENT_SECRET`.\n", "3. Open your `client_secret.json` file in a text editor and copy/paste the content into the `Value` input box of `CLIENT_SECRET`.\n", "4. Toggle the button on the left to allow notebook access to the secret.\n", "\n", "Now you can programmatically create the file instead of uploading it every time. The client secret is also available in all your Google Colab notebooks after you allow access." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "uRg4GMDQLPKl" }, "outputs": [ { "data": { "text/plain": [ "413" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from google.colab import userdata\n", "import pathlib\n", "pathlib.Path('client_secret.json').write_text(userdata.get('CLIENT_SECRET'))" ] }, { "cell_type": "markdown", "metadata": { "id": "RQrh0ol3Oldc" }, "source": [ "### Set the application default credentials\n", "\n", "To convert the `client_secret.json` file into usable credentials, pass its location the `gcloud auth application-default login` command's `--client-id-file` argument.\n", "\n", "The simplified project setup in this tutorial triggers a **Google hasn't verified this app** dialog. This is normal, choose **Continue**.\n", "\n", "You will need to do this step once for every new Google Colab notebook or runtime.\n", "\n", "**Note**: Carefully follow the instructions the following command prints (don't just click the link). Also make sure your local `gcloud --version` is the [latest](https://cloud.google.com/sdk/docs/release-notes) to match the version pre-installed in Google Colab.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "j0dBkV0QOonL" }, "outputs": [], "source": [ "!gcloud auth application-default login \\\n", " --no-browser --client-id-file client_secret.json \\\n", " --scopes https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/generative-language.tuning,https://www.googleapis.com/auth/generative-language.retriever\n" ] }, { "cell_type": "markdown", "metadata": { "id": "TWTBztxTRYb5" }, "source": [ "The specific `scopes` you need depends on the API you are using. For example, looking at the API reference for [`tunedModels.create`](https://ai.google.dev/api/rest/v1beta/tunedModels/create#authorization-scopes), you will see:\n", "\n", "> Requires one of the following OAuth scopes:\n", ">\n", "> * `https://www.googleapis.com/auth/generative-language.tuning`\n", "\n", "This sample asks for all the scopes for tuning and semantic retrieval, but best practice is to use the smallest set of scopes for security and user confidence." ] }, { "cell_type": "markdown", "metadata": { "id": "FFPBKLapSCkM" }, "source": [ "## Using the Python SDK with OAuth\n", "\n", "The Python SDK will automatically find and use application default credentials." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "9OEoeosRTv-5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m137.4/137.4 kB\u001b[0m \u001b[31m2.7 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n", "\u001b[?25h" ] } ], "source": [ "%pip install -U -q \"google-generativeai>=0.7.2\"" ] }, { "cell_type": "markdown", "metadata": { "id": "r8GgGmTrUCR2" }, "source": [ "Let's do a quick test. Note that you did not set an API key using `genai.configure()`!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TS9l5igubpHO" }, "outputs": [], "source": [ "import google.generativeai as genai\n", "\n", "print('Available base models:', [m.name for m in genai.list_models()])" ] }, { "cell_type": "markdown", "metadata": { "id": "dzSRvbxnUmLo" }, "source": [ "# Appendix" ] }, { "cell_type": "markdown", "metadata": { "id": "arP-ISIBUrdv" }, "source": [ "## Making authenticated REST calls from Colab\n", "\n", "In general, you should use the Python SDK to interact with the Gemini API when possible. This example shows how to make OAuth authenticated REST calls from Python for debugging or testing purposes. It assumes you have already set application default credentials from the Quickstart." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "6V_vD8A2Wm28" }, "outputs": [], "source": [ "import requests\n", "\n", "access_token = !gcloud auth application-default print-access-token\n", "\n", "headers = {\n", " 'Content-Type': 'application/json',\n", " 'Authorization': f'Bearer {access_token[0]}',\n", "}\n", "\n", "response = requests.get('https://generativelanguage.googleapis.com/v1/models', headers=headers)\n", "response_json = response.json()\n", "\n", "# All the model names\n", "for model in response_json['models']:\n", " print(model['name'])" ] }, { "cell_type": "markdown", "metadata": { "id": "lisiHaB8Wwi9" }, "source": [ "### Share a tuned model\n", "\n", "Some beta API features may not be supported by the Python SDK yet. This example shows how to make a REST call to add a permission to a tuned model from Python." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ijMDsUj5o6RL" }, "outputs": [], "source": [ "import requests\n", "\n", "model_name = '' # @param {type:\"string\"}\n", "emailAddress = '' # @param {type:\"string\"}\n", "\n", "\n", "access_token = !gcloud auth application-default print-access-token\n", "\n", "headers = {\n", " 'Content-Type': 'application/json',\n", " 'Authorization': f'Bearer {access_token[0]}',\n", "}\n", "\n", "body = {\n", " 'granteeType': 'USER', # Or 'GROUP' or 'EVERYONE' https://ai.google.dev/api/rest/v1beta/tunedModels.permissions\n", " 'emailAddress': emailAddress, # Optional if 'granteeType': 'EVERYONE'\n", " 'role': 'READER'\n", "}\n", "\n", "response = requests.post(f'https://generativelanguage.googleapis.com/v1beta/tunedModels/{model_name}/permissions', json=body, headers=headers)\n", "print(response.json())\n" ] }, { "cell_type": "markdown", "metadata": { "id": "HnKP_dX_Wnr7" }, "source": [ "## Use a service account to authenticate\n", "\n", "Google Cloud [service accounts](https://cloud.google.com/iam/docs/service-account-overview) are accounts that do not represent a human user. They provide a way to manage authentication and authorization when a human is not directly involved, such as your application calling the Gemini API to fulfill a user request, but not authenticated as the user. A simple way to use service accounts to authenticate with the Gemini API is to use a [service account key](https://cloud.google.com/docs/authentication/provide-credentials-adc#local-key).\n", "\n", "This guide briefly covers how to use service account keys in Google Colab.\n", "\n", "**Important:** Service account keys can be a security risk! For more information, see [best practices for managing service account keys](https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys).\n", "\n", "### 1. Create a service account\n", "\n", "Follow the instructions to [create a service account](https://cloud.google.com/iam/docs/service-accounts-create#creating). The **Console** instructions are easiest if you are doing this manually.\n", "\n", "### 2. Create a service account key\n", "\n", "Follow the instructions to [create a service account key]( https://cloud.google.com/iam/docs/keys-create-delete#creating). Note the name of the downloaded key.\n", "\n", "### 3. Add the service account key to Colab\n", "\n", "1. Open your Google Colab notebook and click on the 🔑 **Secrets** tab in the left panel.\n", "2. Create a new secret with the name `SERVICE_ACCOUNT_KEY`.\n", "3. Open your service account key file in a text editor and copy/paste the content into the `Value` input box of `SERVICE_ACCOUNT_KEY`.\n", "4. Toggle the button on the left to allow notebook access to the secret.\n", "\n", "### 4. Authenticate with the Python SDK by service account key" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "f62ztB6mkRk5" }, "outputs": [], "source": [ "import google.generativeai as genai\n", "import pathlib\n", "from google.colab import userdata\n", "from google.oauth2 import service_account\n", "\n", "pathlib.Path('service_account_key.json').write_text(userdata.get('SERVICE_ACCOUNT_KEY'))\n", "\n", "credentials = service_account.Credentials.from_service_account_file('service_account_key.json')\n", "\n", "# Adjust scopes as needed\n", "scoped_credentials = credentials.with_scopes(\n", " ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/generative-language.retriever'])\n", "\n", "genai.configure(credentials=scoped_credentials)\n", "\n", "print('Available base models:', [m.name for m in genai.list_models()])" ] } ], "metadata": { "colab": { "name": "Authentication_with_OAuth.ipynb", "toc_visible": true }, "google": { "image_path": "/site-assets/images/share.png", "keywords": [ "examples", "googleai", "samplecode", "python", "embed", "function" ] }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }