C.W.K.
Stream
Lesson 04 of 06 · published

인증 방법

~12 min · auth, api-key, oauth, service-account

Level 0Spark
0 XP0/35 lessons0/10 achievements
0/140 XP to next level140 XP to go0% complete

세 가지 인증, 세 가지 use case

모든 Gemini 호출은 자기를 어떻게든 식별해야 돼. 세 패턴 있고, 누가 actor 인가에 따라 옳은 게 결정돼:

  1. API key — application 자체가 actor. 가장 단순. AI Studio 용.
  2. OAuth 2.0 — end user 가 actor 고 앱이 그 user 대신 Gemini 호출. retrieval API 처럼 데이터가 Google account scope 인 경우.
  3. Service account — server-side identity 가 actor. Vertex AI 와 production GCP workload 용.

API key — 30 초 path

AI Studio 에서 key 받고, GEMINI_API_KEY (또는 GOOGLE_API_KEY; 둘 다 set 되면 GOOGLE_API_KEY 우선) 로 세팅하면 SDK 가 자동으로 읽어. 절대 commit 하지 마. 절대 client-side JS 에 박지 마. key 유출 blast radius 는 청구서 + 누군가 그걸로 부끄러운 거 생성하면 평판도.

OAuth 2.0 — user 가 데이터 owner

로그인된 user 로서 (그 사람의 Drive, Gmail, Generative Language retriever data) 행동해야 하는 앱이라면 OAuth 필요. 흐름은 표준 Google OAuth — consent 화면으로 redirect, code 를 refresh + access token 으로 교환, 필요할 때 refresh.

Service account — Vertex 의 production default

Vertex AI 에서는 Application Default Credentials (ADC) 가 권장 패턴. SDK 가 환경에서 credential pick up — service account JSON, workload identity binding, 또는 로컬 gcloud auth application-default login. 코드에 key 없음.

Code

API key path (AI Studio)·bash
# .env (gitignored)
GEMINI_API_KEY=AIzaSy...

# 또는 일회성 shell
export GEMINI_API_KEY=AIzaSy...
코드에서 API key·python
from google import genai

# env 의 GEMINI_API_KEY (또는 GOOGLE_API_KEY) 읽음
client = genai.Client()

# 명시적 (덜 흔함; 테스트에 유용)
client = genai.Client(api_key='AIzaSy...')

# Raw HTTP 등가
# curl 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent' \
#   -H "x-goog-api-key: $GEMINI_API_KEY" \
#   -H 'Content-Type: application/json' \
#   -d '{"contents":[{"parts":[{"text":"Hello"}]}]}'
OAuth — user 대신 행동·python
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
import os

SCOPES = ['https://www.googleapis.com/auth/generative-language.retriever']

def load_creds():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    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)
        with open('token.json', 'w') as f:
            f.write(creds.to_json())
    return creds
Service account / ADC (Vertex)·python
from google import genai

# 로컬 dev: `gcloud auth application-default login` 한 번이면
# ADC 자동 작동.
# Server: GOOGLE_APPLICATION_CREDENTIALS=/path/to/sa.json
#         (또는 GKE/Cloud Run 이면 workload identity)

client = genai.Client(
    vertexai=True,
    project='my-prod-project',
    location='us-central1',
)
# 코드에 key 없음. ADC 가 옳은 credential 자동 resolve.

External links

Exercise

fresh Python venv 에 Gemini 인증 두 path 세팅: (1) 로컬 .env 에서 API key 읽는 거, (2) 위의 OAuth flow 로 개인 Google account 인증. 각 path 로 generateContent 한 호출씩 해서 둘 다 동작 확인. 다음 프로젝트에서 어느 패턴 쓸지 한 문장으로 정해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.