SDK Proxy 인증
SDK Proxy 인증 (OAuth2/JWT 자동 갱신)
JWT 인증이 필요한 LiteLLM Proxy와 함께 LiteLLM Python SDK를 사용할 때 OAuth2/JWT 토큰을 자동으로 획득·갱신하는 방법을 알아봐요.
출처: 문서
본문
개요
LiteLLM Proxy가 OAuth2/OIDC 제공사(Azure AD, Keycloak, Okta, Auth0 등)로 보호된다면, SDK 클라이언트는 모든 요청에 유효한 JWT 토큰이 필요해요. 토큰 수명 주기를 수동 관리하는 대신 litellm.proxy_auth가 이를 자동으로 처리해요:
- 아이덴티티 제공사에서 토큰 획득
- 불필요한 요청을 피하려고 토큰 캐싱
- 만료 전에 토큰 갱신 (60초 버퍼)
- 모든 요청에
Authorization: Bearer <token>헤더 주입
빠른 시작
Azure AD
DefaultAzureCredential:
환경 변수, 관리형 아이덴티티, Azure CLI 등 DefaultAzureCredential 체인 사용:
import litellm
from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
# One-time setup
litellm.proxy_auth = ProxyAuthHandler(
credential=AzureADCredential(), # uses DefaultAzureCredential
scope="api://my-litellm-proxy/.default"
)
litellm.api_base = "https://my-proxy.example.com"
# All requests now include Authorization headers automatically
response = litellm.completion(
model="gpt-5.6-terra",
messages=[{"role": "user", "content": "Hello!"}]
)
특정 Azure AD 앱 등록 사용:
import litellm
from azure.identity import ClientSecretCredential
from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
azure_cred = ClientSecretCredential(
tenant_id="your-tenant-id",
client_id="your-client-id",
client_secret="your-client-secret"
)
litellm.proxy_auth = ProxyAuthHandler(
credential=AzureADCredential(credential=azure_cred),
scope="api://my-litellm-proxy/.default"
)
litellm.api_base = "https://my-proxy.example.com"
response = litellm.completion(
model="gpt-5.6-terra",
messages=[{"role": "user", "content": "Hello!"}]
)
필요 패키지: uv add azure-identity
일반 OAuth2 (Okta, Auth0, Keycloak 등)
client_credentials 권한 부여 유형을 지원하는 모든 OAuth2 제공사에서 동작:
import litellm
from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
litellm.proxy_auth = ProxyAuthHandler(
credential=GenericOAuth2Credential(
client_id="your-client-id",
client_secret="your-client-secret",
token_url="https://your-idp.example.com/oauth2/token"
),
scope="litellm_proxy_api"
)
litellm.api_base = "https://my-proxy.example.com"
response = litellm.completion(
model="gpt-5.6-terra",
messages=[{"role": "user", "content": "Hello!"}]
)
사용자 정의 자격 증명 제공사
어떤 인증 메커니즘이든 TokenCredential 프로토콜을 구현해요:
import time
import litellm
from litellm.proxy_auth import AccessToken, ProxyAuthHandler
class MyCustomCredential:
"""Any class with a get_token(scope) -> AccessToken method works."""
def get_token(self, scope: str) -> AccessToken:
# Your custom logic to obtain a token
token = my_auth_system.get_jwt(scope=scope)
return AccessToken(
token=token,
expires_on=int(time.time()) + 3600
)
litellm.proxy_auth = ProxyAuthHandler(
credential=MyCustomCredential(),
scope="my-scope"
)
지원 엔드포인트
다음에 대해 인증 헤더가 자동 주입돼요:
| 엔드포인트 | 기능 |
|---|---|
| Chat Completions | litellm.completion() / litellm.acompletion() |
| Embeddings | litellm.embedding() / litellm.aembedding() |
동작 방식
- 시작 시
litellm.proxy_auth를 한 번 설정 - 각 SDK 호출(
completion(),embedding()) 시 핸들러가 캐시된 토큰 확인 - 토큰이 없거나 60초 내 만료되면 아이덴티티 제공사에서 새 토큰 요청
Authorization: Bearer <token>헤더가 요청에 주입- 토큰 획득 실패 시 경고가 기록되고 인증 헤더 없이 요청 진행
API 레퍼런스
ProxyAuthHandler
토큰 수명 주기를 관리하는 메인 핸들러.
from litellm.proxy_auth import ProxyAuthHandler
handler = ProxyAuthHandler(
credential="", # required - credential provider
scope="" # required - OAuth2 scope to request
)
| 파라미터 | 타입 | 필수 | 설명 |
|---|---|---|---|
credential |
TokenCredential |
예 | 자격 증명 제공사 (AzureADCredential, GenericOAuth2Credential, 또는 사용자 정의) |
scope |
str |
예 | 토큰을 요청할 OAuth2 scope |
메서드:
| 메서드 | 반환 | 설명 |
|---|---|---|
get_token() |
AccessToken |
필요 시 갱신하며 유효한 토큰 가져오기 |
get_auth_headers() |
dict |
{"Authorization": "Bearer <token>"} 헤더 가져오기 |
AzureADCredential
지연 초기화로 모든 azure-identity 자격 증명을 감싼다.
from litellm.proxy_auth import AzureADCredential
# Uses DefaultAzureCredential (recommended)
cred = AzureADCredential()
# Or wrap a specific azure-identity credential
from azure.identity import ManagedIdentityCredential
cred = AzureADCredential(credential=ManagedIdentityCredential())
GenericOAuth2Credential
어떤 제공사든 표준 OAuth2 client credentials 흐름.
from litellm.proxy_auth import GenericOAuth2Credential
cred = GenericOAuth2Credential(
client_id="your-client-id",
client_secret="your-client-secret",
token_url="https://your-idp.com/oauth2/token"
)
| 파라미터 | 타입 | 필수 | 설명 |
|---|---|---|---|
client_id |
str |
예 | OAuth2 client ID |
client_secret |
str |
예 | OAuth2 client secret |
token_url |
str |
예 | 토큰 엔드포인트 URL |
AccessToken
OAuth2 액세스 토큰을 나타내는 dataclass.
from litellm.proxy_auth import AccessToken
token = AccessToken(
token="eyJhbG...", # JWT string
expires_on=1234567890 # Unix timestamp
)
TokenCredential 프로토콜
이 프로토콜을 구현하는 어떤 클래스든 자격 증명 제공사로 사용 가능:
from litellm.proxy_auth import AccessToken
class MyCredential:
def get_token(self, scope: str) -> AccessToken:
...
제공사별 예시
Keycloak
from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
litellm.proxy_auth = ProxyAuthHandler(
credential=GenericOAuth2Credential(
client_id="litellm-client",
client_secret="your-keycloak-client-secret",
token_url="https://keycloak.example.com/realms/your-realm/protocol/openid-connect/token"
),
scope="openid"
)
Okta
from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
litellm.proxy_auth = ProxyAuthHandler(
credential=GenericOAuth2Credential(
client_id="your-okta-client-id",
client_secret="your-okta-client-secret",
token_url="https://your-org.okta.com/oauth2/default/v1/token"
),
scope="litellm_api"
)
Auth0
from litellm.proxy_auth import GenericOAuth2Credential, ProxyAuthHandler
litellm.proxy_auth = ProxyAuthHandler(
credential=GenericOAuth2Credential(
client_id="your-auth0-client-id",
client_secret="your-auth0-client-secret",
token_url="https://your-tenant.auth0.com/oauth/token"
),
scope="https://my-proxy.example.com/api"
)
Azure AD with Managed Identity
from azure.identity import ManagedIdentityCredential
from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
litellm.proxy_auth = ProxyAuthHandler(
credential=AzureADCredential(
credential=ManagedIdentityCredential()
),
scope="api://my-litellm-proxy/.default"
)
use_litellm_proxy와 결합
use_litellm_proxy와 함께 proxy_auth를 사용해 모든 SDK 요청을 인증된 proxy를 통해 라우팅할 수 있어요:
import os
import litellm
from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler
# Route all requests through the proxy
os.environ["LITELLM_PROXY_API_BASE"] = "https://my-proxy.example.com"
litellm.use_litellm_proxy = True
# Authenticate with OAuth2/JWT
litellm.proxy_auth = ProxyAuthHandler(
credential=AzureADCredential(),
scope="api://my-litellm-proxy/.default"
)
# This request goes through the proxy with automatic JWT auth
response = litellm.completion(
model="vertex_ai/gemini-3.8-flash",
messages=[{"role": "user", "content": "Hello!"}]
)
더 알아보기 (Learn more)
- LiteLLM Python SDK 문서
- Proxy 구성 문서