SPB Git

Repository Public

ephemeral-tokens.md 7.8 KB 216 lines markdown

1> [!WARNING]2> **Preview:** Ephemeral tokens are in [Preview](https://cloud.google.com/products#product-launch-stages).34Ephemeral tokens are short-lived authentication tokens for accessing the Gemini5API through [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API). They are designed to enhance security when6you are connecting directly from a user's device to the API (a7[client-to-server](https://ai.google.dev/gemini-api/docs/live#implementation-approach)8implementation). Like standard API keys, ephemeral tokens can be extracted from9client-side applications such as web browsers or mobile apps. But because10ephemeral tokens expire quickly and can be restricted, they significantly reduce11the security risks in a production environment. You should use them when12accessing the Live API directly from client-side applications to enhance API13key security.1415> [!NOTE]16> **Note:** At this time, ephemeral tokens are only compatible with [Live API](https://ai.google.dev/gemini-api/docs/live).1718## How ephemeral tokens work1920Here's how ephemeral tokens work at a high level:21221. Your client (e.g. web app) authenticates with your backend.232. Your backend requests an ephemeral token from Gemini API's provisioning service.243. Gemini API issues a short-lived token.254. Your backend sends the token to the client for WebSocket connections to Live API. You can do this by swapping your API key with an ephemeral token.265. The client then uses the token as if it were an API key.2728![Ephemeral tokens overview](https://ai.google.dev/static/gemini-api/docs/images/Live_API_01.png)2930This enhances security because even if extracted, the token is short-lived,31unlike a long-lived API key deployed client-side. Since the client sends data32directly to Gemini, this also improves latency and avoids your backends needing33to proxy the real time data.3435## Create an ephemeral token3637Here is a simplified example of how to get an ephemeral token from Gemini.38By default, you'll have 1 minute to start new Live API sessions using the token39from this request (`newSessionExpireTime`), and 30 minutes to send messages over40that connection (`expireTime`).4142### Python4344    import datetime45    from google import genai4647    now = datetime.datetime.now(tz=datetime.timezone.utc)4849    client = genai.Client()5051    token = client.auth_tokens.create(52        config = {53        'uses': 1, # The ephemeral token can only be used to start a single session54        'expire_time': now + datetime.timedelta(minutes=30), # Default is 30 minutes in the future55        # 'expire_time': '2025-05-17T00:00:00Z',   # Accepts isoformat.56        'new_session_expire_time': now + datetime.timedelta(minutes=1), # Default 1 minute in the future57      }58    )5960    # You'll need to pass the value under token.name back to your client to use it6162### JavaScript6364    import { GoogleGenAI } from "@google/genai";6566    const client = new GoogleGenAI({});67    const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();6869    const token = await client.authTokens.create({70        config: {71          uses: 1, // The default72          expireTime: expireTime, // Default is 30 mins73          newSessionExpireTime: new Date(Date.now() + (1 * 60 * 1000)), // Default 1 minute in the future74        },75      });7677### REST7879    curl -X POST "https://generativelanguage.googleapis.com/v1beta/auth_tokens" \80      -H "x-goog-api-key: ${GEMINI_API_KEY}" \81      -H "Content-Type: application/json" \82      -d '{83        "uses": 1,84        "expireTime": "YYYY-MM-DDTHH:MM:SSZ",85        "newSessionExpireTime": "YYYY-MM-DDTHH:MM:SSZ"86      }'8788For `expireTime` value constraints, defaults, and other field specs, see the89[API reference](https://ai.google.dev/api/live#ephemeral-auth-tokens).90Within the `expireTime` timeframe, you'll need91[`sessionResumption`](https://ai.google.dev/gemini-api/docs/live-session#session-resumption) to92reconnect the call every 10 minutes (this can be done with the same token even93if `uses: 1`).9495It's also possible to lock an ephemeral token to a set of configurations. This96might be useful to further improve security of your application and keep your97system instructions on the server side.9899### Python100101    from google import genai102103    client = genai.Client()104105    token = client.auth_tokens.create(106        config = {107        'uses': 1,108        'live_connect_constraints': {109            'model': 'gemini-3.8-live',110            'config': {111                'session_resumption':{},112                'response_modalities':['AUDIO']113            }114        },115        }116    )117118    # You'll need to pass the value under token.name back to your client to use it119120### JavaScript121122    import { GoogleGenAI } from "@google/genai";123124    const client = new GoogleGenAI({});125    const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();126127    const token = await client.authTokens.create({128        config: {129            uses: 1, // The default130            expireTime: expireTime,131            liveConnectConstraints: {132                model: 'gemini-3.8-live',133                config: {134                    sessionResumption: {},135                    responseModalities: ['AUDIO']136                }137            },138        }139    });140141    // You'll need to pass the value under token.name back to your client to use it142143### REST144145    curl -X POST "https://generativelanguage.googleapis.com/v1beta/auth_tokens" \146      -H "x-goog-api-key: ${GEMINI_API_KEY}" \147      -H "Content-Type: application/json" \148      -d '{149        "uses": 1,150        "expireTime": "YYYY-MM-DDTHH:MM:SSZ",151        "liveConnectConstraints": {152          "model": "models/gemini-3.8-live",153          "config": {154            "sessionResumption": {},155            "responseModalities": ["AUDIO"]156          }157        }158      }'159160You can also lock a subset of fields, see the [SDK documentation](https://googleapis.github.io/python-genai/genai.html#genai.types.CreateAuthTokenConfig.lock_additional_fields)161for more info.162163## Connect to Live API with an ephemeral token164165Once you have an ephemeral token, you use it as if it were an API key (but166remember, it only works for the live API, and only with the `v1beta` version of167the API).168169The use of ephemeral tokens only adds value when deploying applications170that follow [client-to-server implementation](https://ai.google.dev/gemini-api/docs/live#implementation-approach) approach.171172### JavaScript173174    import { GoogleGenAI, Modality } from '@google/genai';175176    // Use the token generated in the "Create an ephemeral token" section here177    const ai = new GoogleGenAI({178      apiKey: token.name179    });180    const model = 'gemini-3.8-live';181    const config = { responseModalities: [Modality.AUDIO] };182183    async function main() {184185      const session = await ai.live.connect({186        model: model,187        config: config,188        callbacks: { ... },189      });190191      // Send content...192193      session.close();194    }195196    main();197198> [!NOTE]199> **Note:** If not using the SDK, note that ephemeral tokens must either be passed in an `access_token` query parameter, or in an HTTP `Authorization` prefixed by the [auth-scheme](https://datatracker.ietf.org/doc/html/rfc7235#section-2.1) `Token`.200201See [Get started with Live API](https://ai.google.dev/gemini-api/docs/live) for more examples.202203## Best practices204205- Set a short expiration duration using the `expire_time` parameter.206- Tokens expire, requiring re-initiation of the provisioning process.207- Verify secure authentication for your own backend. Ephemeral tokens will only be as secure as your backend authentication method.208- Generally, avoid using ephemeral tokens for backend-to-Gemini connections, as this path is typically considered secure.209210## Limitations211212Ephemeral tokens are only compatible with [Live API](https://ai.google.dev/gemini-api/docs/live) at this time.213214## What's next215216- Read the Live API [reference](https://ai.google.dev/api/live#ephemeral-auth-tokens) on ephemeral tokens for more information.
Files main
Menu

Theme