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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] JWT Auth - AI Gateway, allow using regular OIDC flow with user info endpoints (#17324)
Ishaan Jaff24f847b84c94
diff --git a/docs/my-website/docs/proxy/guardrails/tool_permission.md b/docs/my-website/docs/proxy/guardrails/tool_permission.mdindex 897c31d9dab..1827333654f 100644--- a/docs/my-website/docs/proxy/guardrails/tool_permission.md+++ b/docs/my-website/docs/proxy/guardrails/tool_permission.md@@ -1,4 +1,3 @@-import Image from '@theme/IdealImage';import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';@@ -14,8 +13,6 @@ LiteLLM provides the LiteLLM Tool Permission Guardrail that lets you control whiOpen the LiteLLM Dashboard, click **Add New Guardrail**, and choose **LiteLLM Tool Permission Guardrail**. This loads the rule builder UI.-<Image img={require('../../../img/create_guard_tool_permission.png')} alt="Configure tool permission guardrail in LiteLLM UI" />-#### Step 2: Define Regex Rules1. Click **Add Rule**.@@ -24,8 +21,6 @@ Open the LiteLLM Dashboard, click **Add New Guardrail**, and choose **LiteLLM To4. Optionally add a regex for tool type (e.g., `^function$`).5. Pick **Allow** or **Deny**.-<Image img={require('../../../img/create_rule_tool_permission.png')} alt="Configure tool permission guardrail in LiteLLM UI" />-#### Step 3: Restrict Tool Arguments (Optional)Select **+ Restrict tool arguments** to attach regex validations to nested paths (dot + `[]` notation). This enforces that sensitive parameters (such as `arguments.to[]`) conform to pre-approved formats.diff --git a/docs/my-website/docs/proxy/token_auth.md b/docs/my-website/docs/proxy/token_auth.mdindex c2a88010d79..c465c1022e4 100644--- a/docs/my-website/docs/proxy/token_auth.md+++ b/docs/my-website/docs/proxy/token_auth.md@@ -407,6 +407,72 @@ general_settings:user_id_upsert: true # 👈 upserts the user to db, if valid email but not in db```+## OIDC UserInfo Endpoint++Use this when your JWT/access token doesn't contain user-identifying information. LiteLLM will call your identity provider's UserInfo endpoint to fetch user details.++### When to Use++- Your JWT is opaque (not self-contained) or lacks user claims+- You need to fetch fresh user information from your identity provider+- Your access tokens don't include email, roles, or other identifying data++### Configuration++```yaml title="config.yaml" showLineNumbers+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"+```++### Flow Diagram++```mermaid+sequenceDiagram+ participant Client+ participant LiteLLM+ participant IdP as Identity Provider++ Client->>LiteLLM: Request with Bearer token+ Note over LiteLLM: Check cache for UserInfo++ LiteLLM->>IdP: GET /userinfo (if not cached)<br/>Authorization: Bearer {token}+ IdP-->>LiteLLM: User data (sub, email, roles)++ Note over LiteLLM: Cache response (TTL: 5min)<br/>Extract user_id, email, roles<br/>Perform RBAC checks++ LiteLLM-->>Client: Authorized/Denied+```++### Example: Azure AD++```yaml title="config.yaml" showLineNumbers+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"+```++### Example: Keycloak++```yaml title="config.yaml" showLineNumbers+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"+```+## [BETA] Control Access with OIDC RolesAllow JWT tokens with supported roles to access the proxy.diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex fe87a70b244..b5b0bd80602 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -3422,6 +3422,9 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):- public_allowed_routes: list of allowed routes for authenticated but unknown litellm role jwt tokens.- enforce_rbac: If true, enforce RBAC for all routes.- custom_validate: A custom function to validates the JWT token.+ - oidc_userinfo_endpoint: OIDC UserInfo endpoint URL. When set along with oidc_userinfo_enabled, LiteLLM will call this endpoint with the access token to retrieve user identity information.+ - oidc_userinfo_enabled: Enable fetching user info from OIDC UserInfo endpoint instead of just decoding JWT token. Default: False.+ - oidc_userinfo_cache_ttl: TTL (in seconds) for caching UserInfo responses. Default: 300s (5 minutes).See `auth_checks.py` for the specific routes"""@@ -3472,6 +3475,21 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):jwt_litellm_role_map: Optional[List[JWTLiteLLMRoleMap]] = Nonesync_user_role_and_teams: bool = False#########################################################+ #########################################################+ # OIDC UserInfo Endpoint Configuration+ oidc_userinfo_endpoint: Optional[str] = Field(+ default=None,+ description="OIDC UserInfo endpoint URL. If set, LiteLLM will call this endpoint with the access token to retrieve user identity information.",+ )+ oidc_userinfo_enabled: bool = Field(+ default=False,+ description="Enable fetching user info from OIDC UserInfo endpoint instead of just decoding JWT token.",+ )+ oidc_userinfo_cache_ttl: float = Field(+ default=300,+ description="TTL (in seconds) for caching UserInfo responses. Default: 300s (5 minutes).",+ )+ #########################################################def __init__(self, **kwargs: Any) -> None:# get the attribute names for this Pydantic modeldiff --git a/litellm/proxy/auth/handle_jwt.py b/litellm/proxy/auth/handle_jwt.pyindex 3e18db2d025..ed6877d1469 100644--- a/litellm/proxy/auth/handle_jwt.py+++ b/litellm/proxy/auth/handle_jwt.py@@ -480,6 +480,71 @@ class JWTHandler:else:return False+ async def get_oidc_userinfo(self, token: str) -> dict:+ """+ Fetch user information from OIDC UserInfo endpoint.++ This follows the OpenID Connect protocol where an access token+ is sent to the identity provider's UserInfo endpoint to retrieve+ user identity information.++ Args:+ token: The access token to use for authentication++ Returns:+ dict: User information from the UserInfo endpoint++ Raises:+ Exception: If UserInfo endpoint is not configured or request fails+ """+ if not self.litellm_jwtauth.oidc_userinfo_endpoint:+ raise Exception(+ "OIDC UserInfo endpoint not configured. Set 'oidc_userinfo_endpoint' in JWT auth config."+ )++ # Check cache first+ cache_key = f"oidc_userinfo_{token[:20]}" # Use first 20 chars of token as cache key+ cached_userinfo = await self.user_api_key_cache.async_get_cache(cache_key)++ if cached_userinfo is not None:+ verbose_proxy_logger.debug("Returning cached OIDC UserInfo")+ return cached_userinfo++ verbose_proxy_logger.debug(+ f"Calling OIDC UserInfo endpoint: {self.litellm_jwtauth.oidc_userinfo_endpoint}"+ )++ try:+ # Call the UserInfo endpoint with the access token+ response = await self.http_handler.get(+ url=self.litellm_jwtauth.oidc_userinfo_endpoint,+ headers={+ "Authorization": f"Bearer {token}",+ "Accept": "application/json",+ },+ )++ if response.status_code != 200:+ raise Exception(+ f"OIDC UserInfo endpoint returned status {response.status_code}: {response.text}"+ )++ userinfo = response.json()+ verbose_proxy_logger.debug(f"Received OIDC UserInfo: {userinfo}")++ # Cache the userinfo response+ await self.user_api_key_cache.async_set_cache(+ key=cache_key,+ value=userinfo,+ ttl=self.litellm_jwtauth.oidc_userinfo_cache_ttl,+ )++ return userinfo++ except Exception as e:+ verbose_proxy_logger.error(f"Error fetching OIDC UserInfo: {str(e)}")+ raise Exception(f"Failed to fetch OIDC UserInfo: {str(e)}")+async def auth_jwt(self, token: str) -> dict:# Supported algos: https://pyjwt.readthedocs.io/en/stable/algorithms.html# "Warning: Make sure not to mix symmetric and asymmetric algorithms that interpret@@ -1077,7 +1142,16 @@ class JWTAuthManager:proxy_logging_obj: ProxyLogging,) -> JWTAuthBuilderResult:"""Main authentication and authorization builder"""- jwt_valid_token: dict = await jwt_handler.auth_jwt(token=api_key)+ # Check if OIDC UserInfo endpoint is enabled+ if jwt_handler.litellm_jwtauth.oidc_userinfo_enabled:+ verbose_proxy_logger.debug(+ "OIDC UserInfo is enabled. Fetching user info from UserInfo endpoint."+ )+ # Use the access token to fetch user info from OIDC UserInfo endpoint+ jwt_valid_token: dict = await jwt_handler.get_oidc_userinfo(token=api_key)+ else:+ # Default behavior: decode and validate the JWT token+ jwt_valid_token = await jwt_handler.auth_jwt(token=api_key)# Check custom validateif jwt_handler.litellm_jwtauth.custom_validate:diff --git a/tests/test_litellm/proxy/auth/test_handle_jwt.py b/tests/test_litellm/proxy/auth/test_handle_jwt.pyindex 8f8f3ced074..603a6928f88 100644--- a/tests/test_litellm/proxy/auth/test_handle_jwt.py+++ b/tests/test_litellm/proxy/auth/test_handle_jwt.py@@ -846,4 +846,229 @@ async def test_auth_builder_returns_team_membership_object():assert result["team_membership"].user_id == _user_id, "team_membership user_id should match"assert result["team_membership"].team_id == _team_id, "team_membership team_id should match"assert result["team_membership"].budget_id == "budget_123", "team_membership budget_id should match"- assert result["team_membership"].spend == 10.5, "team_membership spend should match"\ No newline at end of file+ assert result["team_membership"].spend == 10.5, "team_membership spend should match"+++async def test_auth_builder_with_oidc_userinfo_enabled():+ """Test that auth_builder uses OIDC UserInfo endpoint when enabled"""+ from unittest.mock import MagicMock++ from litellm.caching import DualCache+ from litellm.proxy.utils import ProxyLogging++ # Setup test data+ api_key = "test_access_token"+ request_data = {"model": "gpt-4"}+ general_settings = {"enforce_rbac": False}+ route = "/chat/completions"++ user_object = LiteLLM_UserTable(+ user_id="test_user_1", user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Create JWT handler with OIDC UserInfo enabled+ jwt_handler = JWTHandler()+ user_api_key_cache = DualCache()+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)++ jwt_handler.update_environment(+ prisma_client=None,+ user_api_key_cache=user_api_key_cache,+ litellm_jwtauth=LiteLLM_JWTAuth(+ oidc_userinfo_enabled=True,+ oidc_userinfo_endpoint="https://example.com/oauth2/userinfo",+ user_id_jwt_field="sub",+ user_email_jwt_field="email",+ ),+ )++ # Mock OIDC UserInfo response+ userinfo_response = {+ "sub": "test_user_1",+ "email": "[email protected]",+ "scope": "",+ }++ # Mock all the dependencies+ with patch.object(+ jwt_handler, "get_oidc_userinfo", new_callable=AsyncMock+ ) as mock_get_userinfo, patch.object(+ jwt_handler, "auth_jwt", new_callable=AsyncMock+ ) as mock_auth_jwt, patch.object(+ JWTAuthManager, "check_rbac_role", new_callable=AsyncMock+ ) as mock_check_rbac, patch.object(+ jwt_handler, "get_rbac_role", return_value=None+ ) as mock_get_rbac, patch.object(+ jwt_handler, "get_scopes", return_value=[]+ ) as mock_get_scopes, patch.object(+ jwt_handler, "get_object_id", return_value=None+ ) as mock_get_object_id, patch.object(+ JWTAuthManager,+ "get_user_info",+ new_callable=AsyncMock,+ return_value=("test_user_1", "[email protected]", True),+ ) as mock_get_user_info, patch.object(+ jwt_handler, "get_org_id", return_value=None+ ) as mock_get_org_id, patch.object(+ jwt_handler, "get_end_user_id", return_value=None+ ) as mock_get_end_user_id, patch.object(+ JWTAuthManager, "check_admin_access", new_callable=AsyncMock, return_value=None+ ) as mock_check_admin, patch.object(+ JWTAuthManager,+ "find_and_validate_specific_team_id",+ new_callable=AsyncMock,+ return_value=(None, None),+ ) as mock_find_team, patch.object(+ JWTAuthManager, "get_all_team_ids", return_value=set()+ ) as mock_get_all_team_ids, patch.object(+ JWTAuthManager,+ "find_team_with_model_access",+ new_callable=AsyncMock,+ return_value=(None, None),+ ) as mock_find_team_access, patch.object(+ JWTAuthManager,+ "get_objects",+ new_callable=AsyncMock,+ return_value=(user_object, None, None, None),+ ) as mock_get_objects, patch.object(+ JWTAuthManager, "map_user_to_teams", new_callable=AsyncMock+ ) as mock_map_user, patch.object(+ JWTAuthManager, "validate_object_id", return_value=True+ ) as mock_validate_object, patch.object(+ JWTAuthManager, "sync_user_role_and_teams", new_callable=AsyncMock+ ) as mock_sync_user:+ # Set up mock return values+ mock_get_userinfo.return_value = userinfo_response++ # Call auth_builder+ result = await JWTAuthManager.auth_builder(+ api_key=api_key,+ jwt_handler=jwt_handler,+ request_data=request_data,+ general_settings=general_settings,+ route=route,+ prisma_client=None,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=None,+ proxy_logging_obj=proxy_logging_obj,+ )++ # Verify that get_oidc_userinfo was called instead of auth_jwt+ mock_get_userinfo.assert_called_once_with(token=api_key)+ mock_auth_jwt.assert_not_called() # Should not be called when OIDC is enabled++ # Verify the result+ assert result["user_id"] == "test_user_1"+ assert result["user_object"] == user_object+++async def test_auth_builder_with_oidc_userinfo_disabled():+ """Test that auth_builder uses JWT validation when OIDC UserInfo is disabled"""+ from unittest.mock import MagicMock++ from litellm.caching import DualCache+ from litellm.proxy.utils import ProxyLogging++ # Setup test data+ api_key = "test_jwt_token"+ request_data = {"model": "gpt-4"}+ general_settings = {"enforce_rbac": False}+ route = "/chat/completions"++ user_object = LiteLLM_UserTable(+ user_id="test_user_1", user_role=LitellmUserRoles.INTERNAL_USER+ )++ # Create JWT handler with OIDC UserInfo disabled+ jwt_handler = JWTHandler()+ user_api_key_cache = DualCache()+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)++ jwt_handler.update_environment(+ prisma_client=None,+ user_api_key_cache=user_api_key_cache,+ litellm_jwtauth=LiteLLM_JWTAuth(+ oidc_userinfo_enabled=False, # Disabled+ user_id_jwt_field="sub",+ ),+ )++ # Mock JWT validation response+ jwt_response = {+ "sub": "test_user_1",+ "scope": "",+ }++ # Mock all the dependencies+ with patch.object(+ jwt_handler, "get_oidc_userinfo", new_callable=AsyncMock+ ) as mock_get_userinfo, patch.object(+ jwt_handler, "auth_jwt", new_callable=AsyncMock+ ) as mock_auth_jwt, patch.object(+ JWTAuthManager, "check_rbac_role", new_callable=AsyncMock+ ) as mock_check_rbac, patch.object(+ jwt_handler, "get_rbac_role", return_value=None+ ) as mock_get_rbac, patch.object(+ jwt_handler, "get_scopes", return_value=[]+ ) as mock_get_scopes, patch.object(+ jwt_handler, "get_object_id", return_value=None+ ) as mock_get_object_id, patch.object(+ JWTAuthManager,+ "get_user_info",+ new_callable=AsyncMock,+ return_value=("test_user_1", None, None),+ ) as mock_get_user_info, patch.object(+ jwt_handler, "get_org_id", return_value=None+ ) as mock_get_org_id, patch.object(+ jwt_handler, "get_end_user_id", return_value=None+ ) as mock_get_end_user_id, patch.object(+ JWTAuthManager, "check_admin_access", new_callable=AsyncMock, return_value=None+ ) as mock_check_admin, patch.object(+ JWTAuthManager,+ "find_and_validate_specific_team_id",+ new_callable=AsyncMock,+ return_value=(None, None),+ ) as mock_find_team, patch.object(+ JWTAuthManager, "get_all_team_ids", return_value=set()+ ) as mock_get_all_team_ids, patch.object(+ JWTAuthManager,+ "find_team_with_model_access",+ new_callable=AsyncMock,+ return_value=(None, None),+ ) as mock_find_team_access, patch.object(+ JWTAuthManager,+ "get_objects",+ new_callable=AsyncMock,+ return_value=(user_object, None, None, None),+ ) as mock_get_objects, patch.object(+ JWTAuthManager, "map_user_to_teams", new_callable=AsyncMock+ ) as mock_map_user, patch.object(+ JWTAuthManager, "validate_object_id", return_value=True+ ) as mock_validate_object, patch.object(+ JWTAuthManager, "sync_user_role_and_teams", new_callable=AsyncMock+ ) as mock_sync_user:+ # Set up mock return values+ mock_auth_jwt.return_value = jwt_response++ # Call auth_builder+ result = await JWTAuthManager.auth_builder(+ api_key=api_key,+ jwt_handler=jwt_handler,+ request_data=request_data,+ general_settings=general_settings,+ route=route,+ prisma_client=None,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=None,+ proxy_logging_obj=proxy_logging_obj,+ )++ # Verify that auth_jwt was called instead of get_oidc_userinfo+ mock_auth_jwt.assert_called_once_with(token=api_key)+ mock_get_userinfo.assert_not_called() # Should not be called when OIDC is disabled++ # Verify the result+ assert result["user_id"] == "test_user_1"+ assert result["user_object"] == user_object\ No newline at end of file