> ## AI Agent Context
> Get the complete documentation index at: https://aistudio.google.com/llms.txt
> Use this file to discover all available pages.
> For the full documentation in a single file, fetch: https://aistudio.google.com/llms-full.txt

# Authentication with OAuth quickstart

The easiest way to authenticate to the Gemini API is to configure an API
key, as described in the [Gemini API get started
guide](/docs/get-started). If you need stricter access controls,
you can use OAuth instead. This guide will help
you set up authentication with OAuth.

This guide uses a simplified authentication approach that is appropriate
for a testing environment. For a production environment, learn
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.

## Objectives  {% id="objectives" %}

* Set up your cloud project for OAuth
* Set up application-default-credentials
* Manage credentials in your program instead of using `gcloud auth`

## Prerequisites  {% id="prerequisites" %}

To run this quickstart, you need:

* [A Google Cloud project](https://developers.google.com/workspace/guides/create-project)
* [A local installation of the gcloud CLI](https://cloud.google.com/sdk/docs/install)

## Set up your cloud project  {% id="set-cloud" %}

To complete this quickstart, you first need to setup your Cloud project.

### 1. Enable the API  {% id="enable-api" %}

Before using Google APIs, you need to turn them on in a Google Cloud project.

*   In the Google Cloud console, enable the Google Generative Language API.

  {% button href="https://console.cloud.google.com/flows/enableapi?apiid=generativelanguage.googleapis.com" variant="primary" %}Enable the API{% /button %}


### 2. Configure the OAuth consent screen  {% id="configure-oauth" %}

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.

1. In the Google Cloud console, go to **Menu** >
  **Google Auth platform** > **Overview**.

{% button href="https://console.developers.google.com/auth/overview" variant="primary" %}Go to the Google Auth platform{% /button %}

1.   Complete the project configuration form and set the user type to **External**
  in the **Audience** section.

2.   Complete the rest of the form, accept the User Data Policy terms, and then
  click **Create**.

3.   For now, you can skip adding scopes and click **Save and Continue**. In the
  future, when you create an app for use outside of your Google Workspace
  organization, you must add and verify the authorization scopes that your
  app requires.

4.   Add test users:

  1.      Navigate to the
    [Audience page](https://console.developers.google.com/auth/audience) of the
    Google Auth platform.

  2.      Under **Test users**, click **Add users**.

  3.      Enter your email address and any other authorized test users, then
    click **Save**.



### 3. Authorize credentials for a desktop application  {% id="authorize-credentials" %}

To authenticate as an end user and access user data in your app, you need to
create one or more OAuth 2.0 Client IDs. A client ID is used to identify a
single app to Google's OAuth servers. If your app runs on multiple platforms,
you must create a separate client ID for each platform.

1. In the Google Cloud console, go to **Menu** > **Google Auth platform** >
  **Clients**.

{% button href="https://console.developers.google.com/auth/clients" variant="primary" %}Go to Credentials{% /button %}

1.   Click **Create Client**.

2.   Click **Application type** > **Desktop app**.

3.   In the **Name** field, type a name for the credential. This name is only
  shown in the Google Cloud console.

4.   Click **Create**. The OAuth client created screen appears, showing your new
  Client ID and Client secret.

5.   Click **OK**. The newly created credential appears under **OAuth 2.0 Client
  IDs.**

6.   Click the download button to save the JSON file. It will be saved as
  `client_secret_<identifier>.json`, and rename it to `client_secret.json`
  and move it to your working directory.


## Set up Application Default Credentials  {% id="set-application-default" %}

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.

```posix-terminal
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'
```

The simplified project setup in this tutorial triggers a **"Google hasn't
verified this app."** dialog. This is normal, choose **"continue"**.

This places the resulting token in a well known location so it can be accessed
by `gcloud` or the client libraries.

{% callout type="note" %}
  Note: If running on Colab include `--no-browser` and carefully follow the
  instructions it 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 Colab.

{% /callout %}

```bash
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'
```

Once you have the Application Default Credentials (ADC) set, the client
libraries in most languages need minimal to no help to find them.

### Curl  {% id="curl" %}

The quickest way to test that this is working is to use it to access the REST
API using curl:

```posix-terminal
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  {% id="python" %}

In python the client libraries should find them automatically:

```bash
pip install google-genai
```

A minimal script to test it might be:

```python
from google import genai

client = genai.Client()
print('Available base models:', [m.name for m in client.models.list()])
```

## Manage credentials yourself [Python]  {% id="manage-credentials" %}

In many cases you won't have the `gcloud` command available to create the access
token from the Client ID (`client_secret.json`). Google provides libraries in
many languages to let you manage that process within your app. This section
demonstrates the process, in python. There are equivalent examples of this sort
of procedure, for other languages, available in the
[Drive API documentation](https://developers.google.com/drive/api/quickstart/python)

### 1. Install the necessary libraries  {% id="install-libs" %}

Install the Google client library for Python, and the Gemini client library.

```posix-terminal
pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib

pip install google-genai
```

### 2. Write the credential manager  {% id="write-credentials" %}

To minimize the number of times you have to click through the authorization
screens, create a file called `load_creds.py` in your working directory to
caches a `token.json` file that it can reuse later, or refresh if it expires.

Start with the
following code to convert the `client_secret.json` file to a token usable with
`genai.configure`:

```python
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. Write your program  {% id="write-program" %}

Now create your `script.py`:

```python
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. Run your program  {% id="run-program" %}

In your working directory, run the sample:

```posix-terminal
python script.py
```

The first time you run the script, it opens a browser window and prompts you
to authorize access.

1. If you're not already signed in to your Google Account, you're prompted to
  sign in. If you're signed in to multiple accounts, **be sure to select the
  account you set as a "Test Account" when configuring your project.**

{% callout type="note" %}
  Note: The simplified project setup in this tutorial triggers a **"Google
  hasn't verified this app."** dialog. This is normal, choose **"continue"**.

{% /callout %}

1. Authorization information is stored in the file system, so the next time you
  run the sample code, you aren't prompted for authorization.

You have successfully setup authentication.

