Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

[Feat] JWT Auth - auth allow selecting team_id from request header (#17884)

Ishaan Jaffd38f2410325e
diff --git a/docs/my-website/docs/proxy/token_auth.md b/docs/my-website/docs/proxy/token_auth.md
index 1db1b2a8965..fe928a596cf 100644
--- a/docs/my-website/docs/proxy/token_auth.md
+++ b/docs/my-website/docs/proxy/token_auth.md
@@ -247,6 +247,26 @@ OIDC Auth for API: [**See Walkthrough**](https://www.loom.com/share/00fe2deab59a
- Validate if any group has model access
- If all checks pass, allow the request
+### Select Team via Request Header
+
+When a JWT token contains multiple teams (via `team_ids_jwt_field`), you can explicitly select which team to use for a request by passing the `x-litellm-team-id` header.
+
+```bash
+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"}]
+}'
+```
+
+**Validation:**
+- The team ID in the header must exist in the JWT's `team_ids_jwt_field` list or match `team_id_jwt_field`
+- If an invalid team is specified, a 403 error is returned
+- If no header is provided, LiteLLM auto-selects the first team with access to the requested model
+
### Custom JWT Validate
diff --git a/litellm/proxy/auth/handle_jwt.py b/litellm/proxy/auth/handle_jwt.py
index ed6877d1469..17ff0de9f7b 100644
--- a/litellm/proxy/auth/handle_jwt.py
+++ b/litellm/proxy/auth/handle_jwt.py
@@ -1029,6 +1029,47 @@ class JWTAuthManager:
)
return True
+ @staticmethod
+ def get_team_id_from_header(
+ request_headers: Optional[dict],
+ allowed_team_ids: Set[str],
+ ) -> Optional[str]:
+ """
+ Extract team_id from x-litellm-team-id header if present.
+ Validates that the team is in the user's allowed teams from JWT.
+
+ Args:
+ request_headers: Dictionary of request headers
+ allowed_team_ids: Set of team IDs the user is allowed to access (from JWT)
+
+ Returns:
+ The team_id from header if valid, None otherwise
+
+ Raises:
+ HTTPException: If team_id is provided but not in allowed_team_ids
+ """
+ if not request_headers:
+ return None
+
+ # Normalize headers to lowercase for case-insensitive lookup
+ normalized_headers = {k.lower(): v for k, v in request_headers.items()}
+ header_team_id = normalized_headers.get("x-litellm-team-id")
+
+ if not header_team_id:
+ return None
+
+ # Validate that the team_id is in the allowed teams
+ if header_team_id not in allowed_team_ids:
+ raise HTTPException(
+ status_code=403,
+ detail=f"Team '{header_team_id}' from x-litellm-team-id header is not in your JWT's allowed teams. Allowed teams: {list(allowed_team_ids)}",
+ )
+
+ verbose_proxy_logger.debug(
+ f"Using team_id from x-litellm-team-id header: {header_team_id}"
+ )
+ return header_team_id
+
@staticmethod
async def map_user_to_teams(
user_object: Optional[LiteLLM_UserTable],
@@ -1140,6 +1181,7 @@ class JWTAuthManager:
user_api_key_cache: DualCache,
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
+ request_headers: Optional[dict] = None,
) -> JWTAuthBuilderResult:
"""Main authentication and authorization builder"""
# Check if OIDC UserInfo endpoint is enabled
@@ -1216,9 +1258,28 @@ class JWTAuthManager:
return admin_result
# Get team with model access
- ## SPECIFIC TEAM ID
-
- if not team_id:
+ ## Check if team_id is specified via x-litellm-team-id header
+ all_team_ids = JWTAuthManager.get_all_team_ids(jwt_handler, jwt_valid_token)
+ specific_team_id = jwt_handler.get_team_id(token=jwt_valid_token, default_value=None)
+ if specific_team_id:
+ all_team_ids.add(specific_team_id)
+
+ header_team_id = JWTAuthManager.get_team_id_from_header(
+ request_headers=request_headers,
+ allowed_team_ids=all_team_ids,
+ )
+ if header_team_id:
+ team_id = header_team_id
+ team_object = await get_team_object(
+ team_id=team_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ team_id_upsert=jwt_handler.litellm_jwtauth.team_id_upsert,
+ )
+ elif not team_id:
+ ## SPECIFIC TEAM ID
(
team_id,
team_object,
@@ -1233,7 +1294,6 @@ class JWTAuthManager:
if not team_object and not team_id:
## CHECK USER GROUP ACCESS
- all_team_ids = JWTAuthManager.get_all_team_ids(jwt_handler, jwt_valid_token)
team_id, team_object = await JWTAuthManager.find_team_with_model_access(
team_ids=all_team_ids,
requested_model=request_data.get("model"),
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index a3c78af20f9..d0c284e921c 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -517,6 +517,7 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
parent_otel_span=parent_otel_span,
+ request_headers=dict(request.headers),
)
is_proxy_admin = result["is_proxy_admin"]
diff --git a/tests/test_litellm/proxy/auth/test_handle_jwt.py b/tests/test_litellm/proxy/auth/test_handle_jwt.py
index 603a6928f88..8ecbaced21e 100644
--- a/tests/test_litellm/proxy/auth/test_handle_jwt.py
+++ b/tests/test_litellm/proxy/auth/test_handle_jwt.py
@@ -1071,4 +1071,79 @@ async def test_auth_builder_with_oidc_userinfo_disabled():
# Verify the result
assert result["user_id"] == "test_user_1"
- assert result["user_object"] == user_object
\ No newline at end of file
+ assert result["user_object"] == user_object
+
+
+def test_get_team_id_from_header():
+ """Test get_team_id_from_header returns team when valid, None when missing, raises on invalid."""
+ from fastapi import HTTPException
+
+ # Valid team in allowed list
+ result = JWTAuthManager.get_team_id_from_header(
+ request_headers={"x-litellm-team-id": "team-1"},
+ allowed_team_ids={"team-1", "team-2"},
+ )
+ assert result == "team-1"
+
+ # No header returns None
+ result = JWTAuthManager.get_team_id_from_header(
+ request_headers={"authorization": "Bearer token"},
+ allowed_team_ids={"team-1"},
+ )
+ assert result is None
+
+ # Invalid team raises 403
+ with pytest.raises(HTTPException) as exc_info:
+ JWTAuthManager.get_team_id_from_header(
+ request_headers={"x-litellm-team-id": "invalid-team"},
+ allowed_team_ids={"team-1", "team-2"},
+ )
+ assert exc_info.value.status_code == 403
+
+
+async def test_auth_builder_uses_team_from_header_e2e():
+ """Test auth_builder e2e flow: selects team from x-litellm-team-id header."""
+ from litellm.caching import DualCache
+ from litellm.proxy.utils import ProxyLogging
+
+ jwt_handler = JWTHandler()
+ user_api_key_cache = DualCache()
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ team_ids_jwt_field="groups",
+ user_id_jwt_field="sub",
+ ),
+ )
+
+ team_object = LiteLLM_TeamTable(team_id="team-2")
+ user_object = LiteLLM_UserTable(user_id="user-1", user_role=LitellmUserRoles.INTERNAL_USER)
+
+ with patch.object(jwt_handler, "auth_jwt", new_callable=AsyncMock) as mock_auth_jwt, \
+ patch.object(JWTAuthManager, "check_rbac_role", new_callable=AsyncMock), \
+ patch.object(JWTAuthManager, "check_admin_access", new_callable=AsyncMock, return_value=None), \
+ patch("litellm.proxy.auth.handle_jwt.get_team_object", new_callable=AsyncMock) as mock_get_team, \
+ patch.object(JWTAuthManager, "get_objects", new_callable=AsyncMock, return_value=(user_object, None, None, None)), \
+ patch.object(JWTAuthManager, "map_user_to_teams", new_callable=AsyncMock), \
+ patch.object(JWTAuthManager, "sync_user_role_and_teams", new_callable=AsyncMock):
+
+ mock_auth_jwt.return_value = {"sub": "user-1", "scope": "", "groups": ["team-1", "team-2"]}
+ mock_get_team.return_value = team_object
+
+ result = await JWTAuthManager.auth_builder(
+ api_key="jwt-token",
+ jwt_handler=jwt_handler,
+ request_data={"model": "gpt-4"},
+ general_settings={},
+ route="/chat/completions",
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=ProxyLogging(user_api_key_cache=user_api_key_cache),
+ request_headers={"x-litellm-team-id": "team-2"},
+ )
+
+ assert result["team_id"] == "team-2"
+ assert result["team_object"] == team_object
\ No newline at end of file