Authentication with OAuth quickstart  |  Gemini API  |  Google AI for Developers Skip to main content / English Deutsch Español – América Latina Français Indonesia Italiano Polski Português – Brasil Shqip Tiếng Việt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文 – 简体 中文 – 繁體 日本語 한국어 Get API key Cookbook Community Sign in Docs API reference Gemini API Docs API reference Get API key Cookbook Community Get started Overview Get Started API keys Libraries Pricing Interactions API Coding agent setup Models All models Current: Gemini 3.5 Nano Banana Veo Gemini Omni Flash Lyria 3 Lyria RealTime Imagen Text-to-speech Live Live Translate Embeddings Robotics Core capabilities Text Image Image generation 🍌 Image understanding Video Video overview Video understanding Documents Speech and audio Speech generation Audio understanding Thinking Thinking Thought signatures Structured outputs Function calling Long context Agents Overview Quickstart Antigravity Agent Building managed agents Environments Deep Research Agent Tools Overview Google Search Google Maps Code execution URL context Computer Use File Search Combine Tools and Function calling Live API Overview Get started Get started using the GenAI SDK Get started using raw WebSockets Capabilities Live Translation Tool use Session management Ephemeral tokens Best practices Optimization Overview Batch API Webhooks Flex inference Priority inference Context caching Guides Streaming Background execution File input Input methods Files API OpenAI compatibility Media resolution Token counting Prompt engineering Logs and datasets Get started with logs Data logging and sharing Safety Safety settings Safety guidance Frameworks LangChain & LangGraph CrewAI LlamaIndex Vercel AI SDK Temporal Resources Release notes Deprecations Migration Migrate to Gen AI SDK Migrate to Interactions API Interactions breaking changes (May 2026) Rate limits Billing info API troubleshooting Status Partner and library integrations Google AI Studio Quickstart Vibe code in Build mode Developing Full-Stack Apps Build Android Apps Deploying your app Agents in AI Studio Playground Try out LearnLM Troubleshooting Access for Workspace users Google Cloud Platform Gemini Enterprise Agent Platform Gemini API OAuth authentication Policies Terms of service Available regions Abuse monitoring Feedback information The Interactions API is now generally available. We recommend using this API for access to all the latest features and models. Home Gemini API Docs Send feedback 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. 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 before choosing the access credentials that are appropriate for your app. Objectives Set up your cloud project for OAuth Set up application-default-credentials Manage credentials in your program instead of using gcloud auth Prerequisites To run this quickstart, you need: A Google Cloud project A local installation of the gcloud CLI Set up your cloud project To complete this quickstart, you first need to setup your Cloud project. 1. Enable the 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. Enable the API 2. Configure the OAuth consent screen 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. In the Google Cloud console, go to Menu > Google Auth platform > Overview. Go to the Google Auth platform Complete the project configuration form and set the user type to External in the Audience section. Complete the rest of the form, accept the User Data Policy terms, and then click Create. 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. Add test users: Navigate to the Audience page of the Google Auth platform. Under Test users, click Add users. Enter your email address and any other authorized test users, then click Save. 3. Authorize credentials for a desktop application 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. In the Google Cloud console, go to Menu > Google Auth platform > Clients. Go to Credentials Click Create Client. Click Application type > Desktop app. In the Name field, type a name for the credential. This name is only shown in the Google Cloud console. Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret. Click OK. The newly created credential appears under OAuth 2.0 Client IDs. 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 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. 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. 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 to match Colab. 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 The quickest way to test that this is working is to use it to access the REST API using curl: 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 In python the client libraries should find them automatically: pip install google-genai A minimal script to test it might be: from google import genai client = genai.Client() print('Available base models:', [m.name for m in client.models.list()]) Next steps If that's working you're ready to try Semantic retrieval on your text data. Manage credentials yourself [Python] 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 1. Install the necessary libraries Install the Google client library for Python, and the Gemini client library. pip install --upgrade -q google-api-python-client google-auth-httplib2 google-auth-oauthlib pip install google-genai 2. Write the credential manager 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: 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 Now create your 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. Run your program In your working directory, run the sample: python script.py The first time you run the script, it opens a browser window and prompts you to authorize access. 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. Note: The simplified project setup in this tutorial triggers a "Google hasn't verified this app." dialog. This is normal, choose "continue". 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. Send feedback Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Last updated 2026-07-01 UTC. Need to tell us more? [[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-07-01 UTC."],[],[]] Terms Privacy Manage cookies English Deutsch Español – América Latina Français Indonesia Italiano Polski Português – Brasil Shqip Tiếng Việt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文 – 简体 中文 – 繁體 日本語 한국어