Ephemeral tokens

暫時性權杖是短效驗證權杖,可透過 WebSockets 存取 Gemini API。這些類別旨在強化從使用者裝置直接連線至 API 的安全性 (用戶端到伺服器實作)。與標準 API 金鑰一樣,您可以從用戶端應用程式 (例如網路瀏覽器或行動應用程式) 擷取暫時性權杖。不過,由於暫時性權杖會迅速到期,且可受到限制,因此可大幅降低正式環境中的安全風險。

暫時性權杖的運作方式

以下概略說明暫時性權杖的運作方式:

  1. 您的用戶端 (例如網頁應用程式) 會向後端進行驗證。
  2. 後端會向 Gemini API 的佈建服務要求暫時性權杖。
  3. Gemini API 會發出短期權杖。
  4. 後端會將權杖傳送至用戶端,以便建立連線至 Live API 的 WebSocket。您可以將 API 金鑰換成暫時性權杖。
  5. 接著,用戶端會將權杖當作 API 金鑰使用。

暫時性權杖總覽

這樣一來,即使權杖遭到擷取,其壽命也較短,不像部署在用戶端的 API 金鑰壽命較長。由於用戶端會直接將資料傳送至 Gemini,因此也能縮短延遲時間,避免後端需要代理即時資料。

建立暫時性權杖

以下是如何從 Gemini 取得暫時性權杖的簡易範例。根據預設,您有 1 分鐘的時間,可以使用此要求的符記 (newSessionExpireTime) 啟動新的 Live API 工作階段,並有 30 分鐘的時間,透過該連線傳送訊息 (expireTime)。

Python

import datetime

now = datetime.datetime.now(tz=datetime.timezone.utc)

client = genai.Client(
    http_options={'api_version': 'v1alpha',}
)

token = client.auth_tokens.create(
    config = {
    'uses': 1, # The ephemeral token can only be used to start a single session
    'expire_time': now + datetime.timedelta(minutes=30), # Default is 30 minutes in the future
    # 'expire_time': '2025-05-17T00:00:00Z',   # Accepts isoformat.
    'new_session_expire_time': now + datetime.timedelta(minutes=1), # Default 1 minute in the future
    'http_options': {'api_version': 'v1alpha'},
  }
)

# You'll need to pass the value under token.name back to your client to use it

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();

  const token: AuthToken = await client.authTokens.create({
    config: {
      uses: 1, // The default
      expireTime: expireTime // Default is 30 mins
      newSessionExpireTime: new Date(Date.now() + (1 * 60 * 1000)), // Default 1 minute in the future
      httpOptions: {apiVersion: 'v1alpha'},
    },
  });

如需 expireTime 值限制、預設值和其他欄位規格,請參閱 API 參考資料。在 expireTime 時間範圍內,您需要每 10 分鐘呼叫一次 sessionResumption (即使 uses: 1 也能使用相同的權杖)。

您也可以將暫時性權杖鎖定在一系列設定中。這可能有助於進一步提升應用程式的安全性,並將系統指示保留在伺服器端。

Python

client = genai.Client(
    http_options={'api_version': 'v1alpha',}
)

token = client.auth_tokens.create(
    config = {
    'uses': 1,
    'live_connect_constraints': {
        'model': 'gemini-2.0-flash-live-001',
        'config': {
            'session_resumption':{},
            'temperature':0.7,
            'response_modalities':['TEXT']
        }
    },
    'http_options': {'api_version': 'v1alpha'},
    }
)

# You'll need to pass the value under token.name back to your client to use it

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});
const expireTime = new Date(Date.now() + 30 * 60 * 1000).toISOString();

const token = await client.authTokens.create({
    config: {
        uses: 1, // The default
        expireTime: expireTime,
        liveConnectConstraints: {
            model: 'gemini-2.0-flash-live-001',
            config: {
                sessionResumption: {},
                temperature: 0.7,
                responseModalities: ['TEXT']
            }
        },
        httpOptions: {
            apiVersion: 'v1alpha'
        }
    }
});

// You'll need to pass the value under token.name back to your client to use it

您也可以鎖定部分欄位,詳情請參閱 SDK 說明文件

使用暫時性權杖連線至 Live API

以下是透過暫時性權杖連線至 Live API 的範例。請注意,只有在部署遵循用戶端至伺服器導入方法的應用程式時,使用暫時性權杖才會帶來價值。

JavaScript

import { GoogleGenAI, Modality } from '@google/genai';

// Use the token generated in the "Create an ephemeral token" section here
const ai = new GoogleGenAI({});
const model = 'gemini-2.0-flash-live-001';
const config = { responseModalities: [Modality.TEXT] };

async function main() {

  const session = await ai.live.connect({
    model: model,
    config: config,
    callbacks: { ... },
  });

  // Send content...

  session.close();
}

main();

如需更多範例,請參閱「開始使用 Live API」。

最佳做法

  • 使用 expire_time 參數設定較短的到期時間長度。
  • 權杖到期,需要重新啟動佈建程序。
  • 驗證您自己的後端安全驗證機制。暫時性權杖的安全性僅與後端驗證方法相同。
  • 一般來說,請避免在後端到 Gemini 連線中使用暫時性權杖,因為這個路徑通常被視為安全。

限制

目前,暫時性權杖僅與 Live API 相容。

後續步驟

  • 如需進一步瞭解,請參閱 Live API 的參考資料,瞭解如何使用暫時性權杖。