OIDC - 基于 JWT 的认证
使用 JWT 对代理进行管理员/用户/项目身份验证。
想要在不分发 API 密钥的情况下实现基于用户的模型限制、消费限额和速率限制?请参阅 JWT → 虚拟密钥映射 —— 为 JWT 身份验证用户(例如 Claude Code + SSO)提供企业级细粒度访问控制。
用法
第 1 步:设置代理
JWT_PUBLIC_KEY_URL:这是您的 OpenID 提供商的公钥端点。通常是{openid-provider-base-url}/.well-known/openid-configuration/jwks。对于 Keycloak,它是{keycloak_base_url}/realms/{your-realm}/protocol/openid-connect/certs。JWT_AUDIENCE:这是用于解码 JWT 的受众(Audience)。如果未设置,解码步骤将不会验证受众。
export JWT_PUBLIC_KEY_URL="" # "https://demo.duendesoftware.com/.well-known/openid-configuration/jwks"
- 在您的配置中设置
enable_jwt_auth。这将告知代理检查令牌是否为 JWT 令牌。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
model_list:
- model_name: azure-gpt-3.5
litellm_params:
model: azure/<your-deployment-name>
api_base: os.environ/AZURE_API_BASE
api_key: os.environ/AZURE_API_KEY
api_version: "2023-07-01-preview"
第 2 步:创建带有范围(Scopes)的 JWT
- 管理员
- 项目
在您的 OpenID 提供商(例如 Keycloak)中创建一个名为 litellm_proxy_admin 的客户端范围。
在生成 JWT 时,授予您的用户 litellm_proxy_admin 范围。
curl --location ' 'https://demo.duendesoftware.com/connect/token'' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id={CLIENT_ID}' \
--data-urlencode 'client_secret={CLIENT_SECRET}' \
--data-urlencode 'username=test-{USERNAME}' \
--data-urlencode 'password={USER_PASSWORD}' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'scope=litellm_proxy_admin' # 👈 grant this scope
在您的 OpenID 提供商(例如 Keycloak)上为您的项目创建 JWT。
curl --location ' 'https://demo.duendesoftware.com/connect/token'' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id={CLIENT_ID}' \ # 👈 project id
--data-urlencode 'client_secret={CLIENT_SECRET}' \
--data-urlencode 'grant_type=client_credential' \
第 3 步:测试您的 JWT
- /key/generate
- /chat/completions
curl --location '{proxy_base_url}/key/generate' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1NiI...' \
--header 'Content-Type: application/json' \
--data '{}'
curl --location 'http://0.0.0.0:4000/v1/chat/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1...' \
--data '{"model": "azure-gpt-3.5", "messages": [ { "role": "user", "content": "What's the weather like in Boston today?" } ]}'
高级功能
多个 OIDC 提供商
如果您希望 LiteLLM 针对多个 OIDC 提供商(例如 Google Cloud、GitHub Auth)验证您的 JWT,请使用此功能。
在环境中将 JWT_PUBLIC_KEY_URL 设置为 OIDC 提供商 URL 的逗号分隔列表。
export JWT_PUBLIC_KEY_URL="https://demo.duendesoftware.com/.well-known/openid-configuration/jwks,https://#/.well-known/openid-configuration/jwks"
Kubernetes ServiceAccount 身份验证
使用 Kubernetes ServiceAccount 令牌来验证集群中运行的工作负载。当您希望 Pod 使用其原生 Kubernetes 身份向 LiteLLM 进行身份验证时,这非常有用。
先决条件
- 您的 Kubernetes 集群必须启用 ServiceAccount 令牌投影(Kubernetes 1.20+ 默认启用)
- 必须可以访问集群的 OIDC 颁发者(对于 EKS、GKE、AKS,这是自动的)
第 1 步:配置 OIDC 发现 URL
将 JWT_PUBLIC_KEY_URL 设置为您集群的 OIDC 发现端点
- Amazon EKS
- Google GKE
- Azure AKS
- 自托管
# Get your EKS OIDC issuer URL
aws eks describe-cluster --name <cluster-name> --query "cluster.identity.oidc.issuer" --output text
# Set the JWKS URL (append /keys to the issuer URL)
export JWT_PUBLIC_KEY_URL="https://oidc.eks.<region>.amazonaws.com/id/<id>/keys"
# GKE uses Google's OIDC provider
export JWT_PUBLIC_KEY_URL="https://container.googleapis.com/v1/projects/<project>/locations/<location>/clusters/<cluster>/jwks"
# Get your AKS OIDC issuer URL
az aks show --name <cluster-name> --resource-group <resource-group> --query "oidcIssuerProfile.issuerUrl" -o tsv
# Set the JWKS URL
export JWT_PUBLIC_KEY_URL="<issuer-url>/openid/v1/jwks"
# For self-managed clusters, check your API server's --service-account-issuer flag
# The JWKS endpoint is typically at:
export JWT_PUBLIC_KEY_URL="https://<api-server>/openid/v1/jwks"
第 2 步:配置 LiteLLM
配置 LiteLLM 以从 Kubernetes ServiceAccount 令牌中提取身份信息
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
# Use namespace as team identifier (resolves via team_alias in DB)
team_alias_jwt_field: "kubernetes\.io.namespace"
第 3 步:创建 ServiceAccount 并配置 Pod
创建一个带有关联 Secret 的 ServiceAccount,并配置您的 Pod 以使用该令牌
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-llm-client
namespace: my-app
---
apiVersion: v1
kind: Secret
metadata:
name: my-llm-client-token
namespace: my-app
annotations:
kubernetes.io/service-account.name: my-llm-client
type: kubernetes.io/service-account-token
---
apiVersion: v1
kind: Pod
metadata:
name: llm-client-pod
namespace: my-app
spec:
serviceAccountName: my-llm-client
containers:
- name: app
image: my-app:latest
env:
- name: LITELLM_TOKEN
valueFrom:
secretKeyRef:
name: my-llm-client-token
key: token
在 LiteLLM 中设置预期的受众(Audience)
export JWT_AUDIENCE="https://kubernetes.default.svc"
第 4 步:为命名空间创建团队
在 LiteLLM 中创建一个与命名空间匹配的团队(使用 team_alias)
curl -X POST 'http://0.0.0.0:4000/team/new' \
-H 'Authorization: Bearer <PROXY_MASTER_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"team_alias": "my-app",
"team_id": "my-app",
"models": ["gpt-4", "claude-sonnet-4-20250514"]
}'
第 5 步:使用令牌
在 Pod 内部,令牌可通过 LITELLM_TOKEN 环境变量获取
# Make a request to LiteLLM using the env var
curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $LITELLM_TOKEN" \
-d '{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello!"}]
}'
示例:ServiceAccount 令牌结构
Kubernetes ServiceAccount 令牌如下所示
{
"aud": ["litellm-proxy"],
"exp": 1234567890,
"iat": 1234567890,
"iss": "https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLE",
"kubernetes.io": {
"namespace": "my-app",
"pod": {
"name": "llm-client-pod",
"uid": "pod-uid"
},
"serviceaccount": {
"name": "my-llm-client",
"uid": "sa-uid"
}
},
"nbf": 1234567890,
"sub": "system:serviceaccount:my-app:my-llm-client"
}
进阶:使用名称解析将命名空间映射到团队
使用 team_alias_jwt_field 自动将命名空间解析为团队
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
user_id_jwt_field: "sub"
# Map the namespace to team_alias in the database
team_alias_jwt_field: "kubernetes\.io.namespace"
user_id_upsert: true
这样,production 命名空间中的 Pod 将自动与具有 team_alias: production 的团队关联。
设置可接受的 JWT 范围名称
更改 JWT “scopes” 中的字符串,LiteLLM 将评估该字符串以查看用户是否具有管理员访问权限。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
admin_jwt_scope: "litellm-proxy-admin"
跟踪最终用户/内部用户/团队/组织
设置 JWT 令牌中的字段,该字段对应于 LiteLLM 用户/团队/组织。
注意: 所有 JWT 字段都支持点表示法来访问嵌套声明(例如,"user.sub", "resource_access.client.roles")。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
admin_jwt_scope: "litellm-proxy-admin"
team_id_jwt_field: "client_id" # 👈 CAN BE ANY FIELD (supports dot notation for nested claims)
user_id_jwt_field: "sub" # 👈 CAN BE ANY FIELD (supports dot notation for nested claims)
org_id_jwt_field: "org_id" # 👈 CAN BE ANY FIELD (supports dot notation for nested claims)
end_user_id_jwt_field: "customer_id" # 👈 CAN BE ANY FIELD (supports dot notation for nested claims)
预期 JWT(扁平结构)
{
"client_id": "my-unique-team",
"sub": "my-unique-user",
"org_id": "my-unique-org"
}
或者使用点表示法的嵌套结构
{
"user": {
"sub": "my-unique-user",
"email": "user@example.com"
},
"tenant": {
"team_id": "my-unique-team"
},
"organization": {
"id": "my-unique-org"
}
}
嵌套示例的配置
litellm_jwtauth:
user_id_jwt_field: "user.sub"
user_email_jwt_field: "user.email"
team_id_jwt_field: "tenant.team_id"
org_id_jwt_field: "organization.id"
现在,对于每次调用,LiteLLM 都会自动更新数据库中用户/团队/组织的支出。
按名称(别名)而不是 ID 解析
有时您的 JWT 令牌包含人类可读的名称而不是数据库 ID。LiteLLM 可以通过在数据库中查找这些名称将它们解析为 ID。
用例: 您的 IDP 在 JWT 中提供了团队/组织名称,但 LiteLLM 需要实际的数据库 ID 来进行支出跟踪和访问控制。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
# Name-based fields (resolved via database lookup)
team_alias_jwt_field: "team_alias" # Resolves team by team_alias in DB
org_alias_jwt_field: "org_alias" # Resolves org by organization_alias in DB
预期 JWT
{
"sub": "user-123",
"team_alias": "engineering-team",
"org_alias": "acme-corp"
}
工作原理
- LiteLLM 从配置的 JWT 字段中提取名称
- 通过其别名字段在数据库中查找实体
- 团队:
LiteLLM_TeamTable中的team_alias列 - 组织:
LiteLLM_OrganizationTable中的organization_alias列
- 团队:
- 将解析出的 ID 用于支出跟踪和访问控制
优先级: ID 字段始终优先于名称字段。如果同时配置了 team_id_jwt_field 和 team_alias_jwt_field,且 JWT 中存在这两个值,则将使用 ID。
# Example: ID takes precedence
litellm_jwtauth:
team_id_jwt_field: "team_id" # Used if present in JWT
team_alias_jwt_field: "team_alias" # Fallback if team_id not present
嵌套字段: 名称字段也支持嵌套声明的点表示法
litellm_jwtauth:
team_alias_jwt_field: "organization.team.name"
org_alias_jwt_field: "company.name"
重要提示
- 实体(团队/组织)必须已经在数据库中存在,且具有匹配的别名
- 别名应该是唯一的——如果多个实体共享同一个别名,将返回错误
- 名称解析增加了数据库查找,因此直接使用 ID 性能会稍好一些
JWT 范围(Scopes)
JWT-Auth 令牌上的范围看起来是这样的
可以是列表
scope: ["litellm-proxy-admin",...]
可以是空格分隔的字符串
scope: "litellm-proxy-admin ..."
使用团队控制模型访问
- 指定包含用户所属团队 ID 的 JWT 字段。
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
user_id_jwt_field: "sub"
team_ids_jwt_field: "groups"
user_id_upsert: true # add user_id to the db if they don't exist
enforce_team_based_model_access: true # don't allow users to access models unless the team has access
这是假设您的令牌如下所示
{
...,
"sub": "my-unique-user",
"groups": ["team_id_1", "team_id_2"]
}
- 在 LiteLLM 上创建团队
curl -X POST '<PROXY_BASE_URL>/team/new' \
-H 'Authorization: Bearer <PROXY_MASTER_KEY>' \
-H 'Content-Type: application/json' \
-D '{
"team_alias": "team_1",
"team_id": "team_id_1" # 👈 MUST BE THE SAME AS THE SSO GROUP ID
}'
- 测试流程
UI 的 SSO: 查看演练
API 的 OIDC 身份验证: 查看演练
流程
- 验证用户 ID 是否在数据库 (LiteLLM_UserTable) 中
- 验证任何群组是否在数据库 (LiteLLM_TeamTable) 中
- 验证是否有任何群组拥有模型访问权限
- 如果所有检查通过,则允许请求
通过请求头选择团队
当 JWT 令牌包含多个团队(通过 team_ids_jwt_field)时,您可以通过传递 x-litellm-team-id 头来显式选择用于请求的团队。
curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <your-jwt-token>' \
-H 'x-litellm-team-id: team_id_2' \
-d '{
"model": "gpt-4",
"messages": [{"role": "user", "content": "Hello"}]
}'
验证
- 头中的团队 ID 必须存在于 JWT 的
team_ids_jwt_field列表中或匹配team_id_jwt_field - 如果指定了无效团队,则返回 403 错误
- 如果未提供头,LiteLLM 会自动选择第一个有权访问请求模型的团队
自定义 JWT 验证
如果您需要额外的验证方式来确认令牌是否对 LiteLLM 代理有效,请使用自定义逻辑验证 JWT 令牌。
1. 设置自定义验证函数
from typing import Literal
def my_custom_validate(token: str) -> Literal[True]:
"""
Only allow tokens with tenant-id == "my-unique-tenant", and claims == ["proxy-admin"]
"""
allowed_tenants = ["my-unique-tenant"]
allowed_claims = ["proxy-admin"]
if token["tenant_id"] not in allowed_tenants:
raise Exception("Invalid JWT token")
if token["claims"] not in allowed_claims:
raise Exception("Invalid JWT token")
return True
2. 设置 config.yaml
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
user_id_jwt_field: "sub"
team_id_jwt_field: "tenant_id"
user_id_upsert: True
custom_validate: custom_validate.my_custom_validate # 👈 custom validate function
3. 测试流程
预期 JWT
{
"sub": "my-unique-user",
"tenant_id": "INVALID_TENANT",
"claims": ["proxy-admin"]
}
预期响应
{
"error": "Invalid JWT token"
}
允许的路由
通过配置指定 JWT 可以访问哪些路由。
默认情况下
- 管理员:只能访问管理路由 (
/team/*,/key/*,/user/*) - 团队:只能访问 openai 路由 (
/chat/completions等) + 信息路由 (/*/info)
管理路由
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
admin_jwt_scope: "litellm-proxy-admin"
admin_allowed_routes: ["/v1/embeddings"]
团队路由
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
...
team_id_jwt_field: "litellm-team" # 👈 Set field in the JWT token that stores the team ID
team_allowed_routes: ["/v1/chat/completions"] # 👈 Set accepted routes
为团队允许其他提供商路由
要使团队 JWT 令牌能够访问 Anthropic 风格的端点(例如 /v1/messages),请更新 litellm_jwtauth 配置中的 team_allowed_routes。team_allowed_routes 支持以下值:
- 来自
LiteLLMRoutes的命名路由组(例如openai_routes,anthropic_routes,info_routes,mapped_pass_through_routes)。
以下是您可以使用的路由组的快速参考以及每组的代表性路由示例。如果需要完整列表,请参阅 litellm/proxy/_types.py 中的 LiteLLMRoutes 枚举以获取权威列表。
| 路由组 | 包含内容 | 代表性路由 |
|---|---|---|
openai_routes | 兼容 OpenAI 的 REST 端点(聊天、补全、嵌入、图像、响应、模型等) | /v1/chat/completions, /v1/completions, /v1/embeddings, /v1/images/generations, /v1/models |
anthropic_routes | Anthropic 风格的端点 (/v1/messages 及相关) | /v1/messages, /v1/messages/count_tokens, /v1/skills |
mapped_pass_through_routes | 提供商特定的直通路由前缀(例如,通过 /anthropic 代理的 Anthropic)。与 mapped_pass_through_routes 一起使用以进行提供商通配符映射 | /anthropic/*, /vertex-ai/*, /bedrock/* |
passthrough_routes_wildcard | 提供商的通配符映射(例如 /anthropic/*) - 代理使用的预计算通配符列表 | /anthropic/*, /vllm/* |
google_routes | Google 特定(例如 Vertex / 批处理端点) | /v1beta/models/{model_name}:generateContent |
mcp_routes | 内部 MCP 管理端点 | /mcp/tools, /mcp/tools/call |
info_routes | UI 使用的只读及信息端点 | /key/info, /team/info, /v1/models |
management_routes | 仅限管理员的管理端点(创建/更新/删除用户/团队/模型) | /team/new, /key/generate, /model/new |
spend_tracking_routes | 与预算/支出相关的端点 | /spend/logs, /spend/keys |
public_routes | 公共和未经身份验证的端点 | /, /routes, /.well-known/litellm-ui-config |
注意:llm_api_routes 是 OpenAI、Anthropic、Google、直通和其他 LLM 路由的并集 (openai_routes + anthropic_routes + google_routes + mapped_pass_through_routes + passthrough_routes_wildcard + apply_guardrail_routes + mcp_routes + litellm_native_routes)。
默认值(如果您未在 litellm_jwtauth 中覆盖它们,代理将使用这些值)
admin_jwt_scope:litellm_proxy_adminadmin_allowed_routes(默认):management_routes,spend_tracking_routes,global_spend_tracking_routes,info_routesteam_allowed_routes(默认):openai_routes,info_routespublic_allowed_routes(默认):public_routes
示例:允许团队 JWT 调用 Anthropic /v1/messages(按路由组或显式路由字符串)
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
team_ids_jwt_field: "team_ids"
team_allowed_routes: ["openai_routes", "info_routes", "anthropic_routes"]
或仅有选择地允许确切的 Anthropic 消息端点
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
team_ids_jwt_field: "team_ids"
team_allowed_routes: ["/v1/messages", "info_routes"]
缓存公钥
控制公钥的缓存时长(以秒为单位)。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
admin_jwt_scope: "litellm-proxy-admin"
admin_allowed_routes: ["/v1/embeddings"]
public_key_ttl: 600 # 👈 KEY CHANGE
自定义 JWT 字段
设置一个包含 team_id 的自定义字段。默认情况下,检查 'client_id' 字段。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
team_id_jwt_field: "client_id" # 👈 KEY CHANGE
封禁团队
要封禁特定团队 ID 的所有请求,请使用 /team/block
封禁团队
curl --location 'http://0.0.0.0:4000/team/block' \
--header 'Authorization: Bearer <admin-token>' \
--header 'Content-Type: application/json' \
--data '{
"team_id": "litellm-test-client-id-new" # 👈 set team id
}'
解封团队
curl --location 'http://0.0.0.0:4000/team/unblock' \
--header 'Authorization: Bearer <admin-token>' \
--header 'Content-Type: application/json' \
--data '{
"team_id": "litellm-test-client-id-new" # 👈 set team id
}'
Upsert 用户 + 允许的电子邮件域
允许属于特定电子邮件域的用户自动访问代理。
注意: user_allowed_email_domain 是可选的。如果未指定,所有用户无论其电子邮件域如何,都将被允许访问。
general_settings:
master_key: sk-1234
enable_jwt_auth: True
litellm_jwtauth:
user_email_jwt_field: "email" # 👈 checks 'email' field in jwt payload
user_allowed_email_domain: "my-co.com" # 👈 OPTIONAL - allows user@my-co.com to call proxy
user_id_upsert: true # 👈 upserts the user to db, if valid email but not in db
OIDC UserInfo 端点
当您的 JWT/访问令牌不包含用户标识信息时,请使用此功能。LiteLLM 将调用您的身份提供商的 UserInfo 端点以获取用户详细信息。
何时使用
- 您的 JWT 是不透明的(非自包含)或缺少用户声明
- 您需要从身份提供商处获取最新的用户信息
- 您的访问令牌不包含电子邮件、角色或其他标识数据
配置
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
# Enable OIDC UserInfo endpoint
oidc_userinfo_enabled: true
oidc_userinfo_endpoint: "https://your-idp.com/oauth2/userinfo"
oidc_userinfo_cache_ttl: 300 # Cache for 5 minutes (default: 300)
# Map fields from UserInfo response
user_id_jwt_field: "sub"
user_email_jwt_field: "email"
user_roles_jwt_field: "roles"
流程图
示例:Azure AD
litellm_jwtauth:
oidc_userinfo_enabled: true
oidc_userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo"
user_id_jwt_field: "sub"
user_email_jwt_field: "email"
示例:Keycloak
litellm_jwtauth:
oidc_userinfo_enabled: true
oidc_userinfo_endpoint: "https://keycloak.example.com/realms/your-realm/protocol/openid-connect/userinfo"
user_id_jwt_field: "sub"
user_roles_jwt_field: "resource_access.your-client.roles"
将 JWT 形态的机器令牌路由到 OAuth2
在以下情况下使用
enable_jwt_auth: true用于标准 JWT 验证- 机器令牌具有 JWT 形态,应根据声明路由到 OAuth2
routing_overrides 支持两种操作模式
- 选择性模式:设置
enable_oauth2_auth: false,仅将匹配的 JWT 发送到 LLM + 信息路由上的 OAuth2 - 全局模式:设置
enable_oauth2_auth: true,同时在 LLM + 信息路由上启用 OAuth2
general_settings:
enable_jwt_auth: true
enable_oauth2_auth: false
litellm_jwtauth:
user_id_jwt_field: "sub"
routing_overrides:
- iss: "machine-issuer.example.com"
client_id: "MID_LITELLM"
path: "oauth2"
匹配行为
- 当所有配置的选择器与相应的令牌声明匹配时(AND 语义),规则即匹配。
- 支持的选择器:
iss(必需),client_id(可选),scope(可选),aud(可选)。 - 选择器值可以是单个字符串或字符串列表(声明必须至少匹配一个条目,使用以下规则)。
- 通配符: 选择器可以使用 shell 风格的
*和?。匹配是区分大小写的——请使用您的 IdP 在 JWT 声明中输出的相同大小写。 scope声明作为空格分隔的字符串: OAuth/OIDC 通常将scope发送为一个字符串(例如openid profile App:LiteLLM)。LiteLLM 仅在匹配scope选择器时拆分该字符串,因此像App:LiteLLM这样的配置值可以匹配。iss,aud, 和client_id永远不会按空格拆分;使用完整的声明字符串(路由仅使用未经验证的声明进行路径选择;最终身份验证仍会验证令牌)。- 如果没有任何规则匹配,LiteLLM 将继续进行标准 JWT 验证。
示例:scope 和通配符 client_id
general_settings:
enable_jwt_auth: true
enable_oauth2_auth: false
litellm_jwtauth:
routing_overrides:
- iss: "machine-issuer.example.com"
scope: "App:LiteLLM"
client_id: "*MID_LITELLM"
path: "oauth2"
基于列表的覆盖示例
general_settings:
enable_jwt_auth: true
enable_oauth2_auth: false
litellm_jwtauth:
routing_overrides:
- iss: ["machine-issuer.example.com", "backup-issuer.example.com"]
client_id: ["MID_LITELLM", "MID_BACKUP"]
aud: ["api://litellm", "api://fallback"]
path: "oauth2"
[BETA] 使用 OIDC 角色控制访问
允许具有受支持角色的 JWT 令牌访问代理。
让用户和团队无需添加到数据库即可访问代理。
非常重要,设置 enforce_rbac: true 以确保启用 RBAC 系统。
注意: 此功能处于测试阶段,可能会有意外更改。
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
object_id_jwt_field: "oid" # can be either user / team, inferred from the role mapping
roles_jwt_field: "roles"
role_mappings:
- role: litellm.api.consumer
internal_role: "team"
enforce_rbac: true # 👈 VERY IMPORTANT
role_permissions: # default model + endpoint permissions for a role.
- role: team
models: ["anthropic-claude"]
routes: ["/v1/chat/completions"]
environment_variables:
JWT_AUDIENCE: "api://LiteLLM_Proxy" # ensures audience is validated
-
object_id_jwt_field:JWT 令牌中包含对象 ID 的字段。此 ID 可以是用户 ID 或团队 ID。使用此字段代替user_id_jwt_field和team_id_jwt_field。如果同一个字段两者兼有。支持嵌套声明的点表示法(例如"profile.object_id")。 -
roles_jwt_field:JWT 令牌中包含角色的字段。此字段是用户拥有的角色列表。支持嵌套字段的点表示法 - 例如resource_access.litellm-test-client-id.roles。
附加 JWT 字段配置选项
-
team_ids_jwt_field:包含团队 ID 的字段(作为列表)。支持点表示法(例如"groups","teams.ids")。 -
user_email_jwt_field:包含用户电子邮件的字段。支持点表示法(例如"email","user.email")。 -
end_user_id_jwt_field:包含用于成本跟踪的最终用户 ID 的字段。支持点表示法(例如"customer_id","customer.id")。 -
role_mappings:角色映射列表。将 JWT 令牌中接收到的角色映射到 LiteLLM 上的内部角色。 -
JWT_AUDIENCE:JWT 令牌的受众。这用于验证 JWT 令牌的受众。通过环境变量设置。
示例令牌
{
"aud": "api://LiteLLM_Proxy",
"oid": "eec236bd-0135-4b28-9354-8fc4032d543e",
"roles": ["litellm.api.consumer"]
}
角色映射规范
role:JWT 令牌中预期的角色。internal_role:将用于控制访问的 LiteLLM 内部角色。
支持的内部角色
team:团队对象将用于 RBAC 支出跟踪。将其用于跟踪“用例”的支出。internal_user:用户对象将用于 RBAC 支出跟踪。将其用于跟踪“个人用户”的支出。proxy_admin:代理管理员将用于 RBAC 支出跟踪。将其用于授予令牌管理员访问权限。
架构图(控制模型访问)
[BETA] 使用范围控制模型访问
控制 JWT 可以访问哪些模型。设置 enforce_scope_based_access: true 以强制执行基于范围的访问控制。
1. 设置带有范围映射的 config.yaml。
model_list:
- model_name: anthropic-claude
litellm_params:
model: anthropic/claude-3-5-sonnet
api_key: os.environ/ANTHROPIC_API_KEY
- model_name: gpt-3.5-turbo-testing
litellm_params:
model: gpt-3.5-turbo
api_key: os.environ/OPENAI_API_KEY
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
team_id_jwt_field: "client_id" # 👈 set the field in the JWT token that contains the team id
team_id_upsert: true # 👈 upsert the team to db, if team id is not found in db
scope_mappings:
- scope: litellm.api.consumer
models: ["anthropic-claude"]
- scope: litellm.api.gpt_3_5_turbo
models: ["gpt-3.5-turbo-testing"]
enforce_scope_based_access: true # 👈 enforce scope-based access control
enforce_rbac: true # 👈 enforces only a Team/User/ProxyAdmin can access the proxy.
范围映射规范
scope:用于 JWT 令牌的范围。models:JWT 令牌可以访问的模型。值是model_list中的model_name。注意:目前不支持通配符路由。
2. 创建具有正确范围的 JWT。
预期令牌
{
"scope": ["litellm.api.consumer", "litellm.api.gpt_3_5_turbo"] # can be a list or a space-separated string
}
3. 测试流程。
curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer eyJhbGci...' \
-d '{
"model": "gpt-3.5-turbo-testing",
"messages": [
{
"role": "user",
"content": "Hey, how'\''s it going 1234?"
}
]
}'
[BETA] 与 IDP 同步用户角色和团队
自动将用户角色和团队成员身份从您的身份提供商 (IDP) 同步到 LiteLLM 数据库。这确保了 LiteLLM 中的用户权限和团队成员身份与您的 IDP 保持同步。
注意: 此功能处于测试阶段,可能会有意外更改。
使用案例
- 角色同步:当 IDP 中的角色发生更改时,自动更新 LiteLLM 中的用户角色
- 团队成员身份同步:在您的 IDP 和 LiteLLM 之间保持团队成员身份同步
- 集中式访问管理:通过 IDP 管理所有用户权限,同时保持 LiteLLM 功能
设置
1. 配置 JWT 角色映射
将 JWT 令牌中的角色映射到 LiteLLM 用户角色
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
user_id_jwt_field: "sub"
team_ids_jwt_field: "groups"
roles_jwt_field: "roles"
user_id_upsert: true
sync_user_role_and_teams: true # 👈 Enable sync functionality
jwt_litellm_role_map: # 👈 Map JWT roles to LiteLLM roles
- jwt_role: "ADMIN"
litellm_role: "proxy_admin"
- jwt_role: "USER"
litellm_role: "internal_user"
- jwt_role: "VIEWER"
litellm_role: "internal_user"
2. JWT 角色映射规范
jwt_role:JWT 令牌中显示的角色名称。支持使用fnmatch的通配符模式(例如"ADMIN_*"匹配"ADMIN_READ","ADMIN_WRITE"等)litellm_role:对应的 LiteLLM 用户角色
支持的 LiteLLM 角色
proxy_admin:完全管理权限internal_user:标准用户权限internal_user_view_only:只读权限
3. 示例 JWT 令牌
{
"sub": "user-123",
"roles": ["ADMIN"],
"groups": ["team-alpha", "team-beta"],
"iat": 1234567890,
"exp": 1234567890
}
工作原理
当用户使用 JWT 令牌发出请求时
-
角色同步:
- LiteLLM 检查 JWT 中的用户角色是否与数据库中的角色匹配
- 如果不一致,则在 LiteLLM 数据库中更新用户的角色
- 使用
jwt_litellm_role_map将 JWT 角色转换为 LiteLLM 角色
-
团队成员身份同步:
- 比较 JWT 令牌中的团队成员身份与用户在 LiteLLM 中的当前团队
- 将用户添加到 JWT 中发现的新团队
- 将用户从 JWT 中不存在的团队中移除
-
数据库更新:
- 更新在身份验证过程中自动进行
- 无需人工干预
配置选项
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
# Required fields
user_id_jwt_field: "sub"
team_ids_jwt_field: "groups"
roles_jwt_field: "roles"
# Sync configuration
sync_user_role_and_teams: true
user_id_upsert: true
# Role mapping
jwt_litellm_role_map:
- jwt_role: "AI_ADMIN_*" # Wildcard pattern
litellm_role: "proxy_admin"
- jwt_role: "AI_USER"
litellm_role: "internal_user"
重要注意事项
- 性能:同步操作在身份验证期间发生,这可能会增加轻微延迟
- 数据库访问:用户和团队更新需要数据库访问权限
- 团队创建:在同步可以将用户分配给它们之前,JWT 令牌中提到的团队必须已在 LiteLLM 中存在
- 通配符支持:JWT 角色模式支持使用
fnmatch的通配符匹配
测试同步功能
- 创建一个具有初始角色的测试用户:
curl -X POST 'http://0.0.0.0:4000/user/new' \
-H 'Authorization: Bearer <PROXY_MASTER_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"user_id": "user-123",
"user_role": "internal_user"
}'
- 发出一个带有不同角色的 JWT 的请求:
curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <JWT_WITH_ADMIN_ROLE>' \
-d '{
"model": "claude-sonnet-4-20250514",
"messages": [{"role": "user", "content": "Hello"}]
}'
- 验证角色是否已更新:
curl -X GET 'http://0.0.0.0:4000/user/info?user_id=user-123' \
-H 'Authorization: Bearer <PROXY_MASTER_KEY>'
[BETA] JWT 到虚拟密钥映射
将 JWT 身份映射到 LiteLLM 虚拟密钥,以便通过 JWT 身份验证的用户获得每用户预算、速率限制、模型访问控制和支出跟踪。
当 JWT 到来时,LiteLLM 会在映射表中查找配置的声明(例如 email, sub)。如果存在映射,则请求将被视为使用了相应的虚拟密钥 —— 所有虚拟密钥功能均适用。
设置
将 virtual_key_claim_field 添加到您的 JWT 身份验证配置中
general_settings:
enable_jwt_auth: True
litellm_jwtauth:
virtual_key_claim_field: "email" # JWT claim to look up (supports dot notation)
virtual_key_mapping_cache_ttl: 300 # Cache TTL in seconds (default: 300)
管理映射
所有端点都需要管理员身份验证 (Authorization: Bearer <master_key>)。
创建映射 —— 将 JWT 声明值链接到现有的虚拟密钥
curl -X POST https://:4000/jwt/key/mapping/new \
-H "Authorization: Bearer sk-1234" \
-H "Content-Type: application/json" \
-d '{
"jwt_claim_name": "email",
"jwt_claim_value": "user@example.com",
"key": "sk-virtual-key-from-key-generate"
}'
列出映射(分页)
curl https://:4000/jwt/key/mapping/list?page=1&size=50 \
-H "Authorization: Bearer sk-1234"
获取特定映射
curl "https://:4000/jwt/key/mapping/info?id=<mapping-id>" \
-H "Authorization: Bearer sk-1234"
更新映射
curl -X POST https://:4000/jwt/key/mapping/update \
-H "Authorization: Bearer sk-1234" \
-H "Content-Type: application/json" \
-d '{
"id": "<mapping-id>",
"description": "Updated description",
"is_active": true
}'
删除映射
curl -X POST https://:4000/jwt/key/mapping/delete \
-H "Authorization: Bearer sk-1234" \
-H "Content-Type: application/json" \
-d '{"id": "<mapping-id>"}'
工作原理
- 收到带有 JWT 持有者令牌的请求
- LiteLLM 验证 JWT 签名
- 提取配置的声明(例如
email→user@example.com) - 在
LiteLLM_JWTKeyMapping表中查找声明值 - 如果存在映射,则请求继续执行,就像使用了映射的虚拟密钥一样 —— 预算、速率限制、模型访问和支出跟踪全部适用
- 如果不存在映射,则回退到标准 JWT 身份验证(团队级控制)
错误代码
| 代码 | 含义 |
|---|---|
| 409 | 重复映射 —— 该声明名称 + 值的映射已存在 |
| 400 | 提供的密钥与现有的虚拟密钥不匹配 |
| 404 | 未找到映射(用于更新/删除/信息) |
| 403 | 非管理员用户尝试进行映射操作 |