Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(auth): add oidc (#97388)

Reece Jones280b444ca63e
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index 7b50b8d444c1..ef2b08327f10 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -2,25 +2,33 @@ import os
import json
import uuid
import datetime
+from types import SimpleNamespace
from typing import Any, cast
from urllib.parse import parse_qs, urlencode, urlparse
import pytest
import time_machine
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core import mail
from django.core.exceptions import ValidationError
+from django.http import HttpResponse
from django.shortcuts import redirect
-from django.test import override_settings
+from django.test import RequestFactory, override_settings
from django.utils import timezone
+import jwt
+from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
+from requests import Response
from rest_framework import status
-from social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameter
+from social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameter, AuthTokenError
from social_django.models import UserSocialAuth
+from social_django.utils import load_strategy
+from posthog.api.authentication import social_identity_matches_session
+from posthog.api.oidc import MultitenantOIDCAuth
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -54,6 +62,376 @@ GITHUB_MOCK_SETTINGS = {
CURRENT_FOLDER = os.path.dirname(__file__)
+class TestOIDCAuthentication(APILicensedTest):
+ def setUp(self):
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.OIDC, "name": "OIDC"},
+ {"key": AvailableFeature.SSO_ENFORCEMENT, "name": "SSO enforcement"},
+ ]
+ self.organization.save()
+ self.domain = OrganizationDomain.objects.create(
+ organization=self.organization, domain="example.com", verified_at=timezone.now()
+ )
+ self.config = IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="oidc",
+ domain_scope="all",
+ oidc_issuer_url="https://idp.example.com",
+ oidc_client_id="example-client",
+ oidc_credentials={"client_secret": "example-secret"},
+ )
+ request = RequestFactory().get("/login/oidc/", {"email": "[email protected]"})
+ request.session = self.client.session
+ request.session["oidc_config_id"] = str(self.config.id)
+ request.session["oidc_email"] = "[email protected]"
+ request.session["oidc_organization_id"] = self.organization.id
+ self.backend = MultitenantOIDCAuth(load_strategy(request), "https://app.example.com/complete/oidc/")
+
+ @parameterized.expand([("malformed", b"not-json"), ("non_object", b"[]")])
+ def test_oidc_rejects_invalid_discovery_json(self, _name, content):
+ response = Response()
+ response.status_code = 200
+ response._content = content
+ with patch.object(self.backend, "request", return_value=response):
+ with self.assertRaises(AuthFailed):
+ self.backend.get_json("https://idp.example.com/.well-known/openid-configuration")
+
+ @parameterized.expand([("missing_keys", {}), ("non_list_keys", {"keys": {}}), ("non_object_key", {"keys": [None]})])
+ def test_oidc_rejects_invalid_jwks_document(self, _name, document):
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps(document).encode()
+ with (
+ patch.object(self.backend, "jwks_uri", return_value="https://idp.example.com/keys"),
+ patch.object(self.backend, "request", return_value=response),
+ ):
+ with self.assertRaises(AuthFailed):
+ self.backend.get_remote_jwks_keys()
+
+ def test_oidc_rejects_malformed_id_token_header(self):
+ with self.assertRaises(AuthTokenError):
+ self.backend.find_valid_key("not-a-jwt")
+
+ @parameterized.expand(
+ [
+ ("valid", None),
+ ("issuer", {"iss": "https://other.example.com"}),
+ ("audience", {"aud": "other-client"}),
+ ("expired", {"exp": 1}),
+ ("nonce", {"nonce": "wrong-nonce"}),
+ ("authorized_party", {"azp": "other-client"}),
+ ("multiple_audiences", {"aud": ["example-client", "other-client"]}),
+ ]
+ )
+ def test_oidc_validates_signed_id_token(self, _name, overrides):
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ public_key = {**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key())), "kid": "example-key"}
+ discovery = {
+ "issuer": self.config.oidc_issuer_url,
+ "authorization_endpoint": "https://idp.example.com/authorize",
+ "token_endpoint": "https://idp.example.com/token",
+ "jwks_uri": "https://idp.example.com/keys",
+ }
+ with patch.object(self.backend, "get_json", return_value=discovery):
+ nonce = parse_qs(urlparse(self.backend.auth_url()).query)["nonce"][0]
+ claims = {
+ "iss": self.config.oidc_issuer_url,
+ "aud": "example-client",
+ "sub": "example-user",
+ "iat": int(timezone.now().timestamp()),
+ "exp": int(timezone.now().timestamp()) + 60,
+ "nonce": nonce,
+ **(overrides or {}),
+ }
+ token = jwt.encode(claims, private_key, algorithm="RS256", headers={"kid": "example-key"})
+ with patch.object(self.backend, "get_jwks_keys", return_value=[public_key]):
+ if overrides:
+ with self.assertRaises(AuthTokenError):
+ self.backend.validate_and_return_id_token(token, "example-access-token")
+ else:
+ self.assertEqual(self.backend.validate_and_return_id_token(token, "example-access-token"), claims)
+ with self.assertRaises(AuthTokenError):
+ self.backend.validate_and_return_id_token(token, "example-access-token")
+
+ def _complete_oidc_login(
+ self, email: str, *, sub: str = "example-user", name: str = "Example User"
+ ) -> HttpResponse:
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ public_key = {**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key())), "kid": "example-key"}
+ token_response: dict[str, Any] = {}
+
+ def oidc_response(url, method="GET", *args, **kwargs):
+ response = Response()
+ response.status_code = 200
+ data: dict[str, Any]
+ if url.endswith("/.well-known/openid-configuration"):
+ data = {
+ "issuer": self.config.oidc_issuer_url,
+ "authorization_endpoint": "https://idp.example.com/authorize",
+ "token_endpoint": "https://idp.example.com/token",
+ "userinfo_endpoint": "https://idp.example.com/userinfo",
+ "jwks_uri": "https://idp.example.com/keys",
+ }
+ elif url.endswith("/keys"):
+ data = {"keys": [public_key]}
+ elif url.endswith("/userinfo"):
+ self.assertEqual(method, "GET")
+ self.assertEqual(kwargs["headers"], {"Authorization": "Bearer example-access-token"})
+ data = {
+ "sub": sub,
+ "email": email,
+ "email_verified": True,
+ "name": name,
+ }
+ else:
+ self.assertEqual(url, "https://idp.example.com/token")
+ self.assertEqual(method, "POST")
+ self.assertIn("code_verifier", kwargs["data"])
+ data = token_response
+ response._content = json.dumps(data).encode()
+ return response
+
+ with patch.object(MultitenantOIDCAuth, "request", side_effect=oidc_response):
+ response = self.client.get("/login/oidc/", {"email": email})
+ self.assertEqual(response.status_code, 302)
+ params = parse_qs(urlparse(response["Location"]).query)
+ claims = {
+ "iss": self.config.oidc_issuer_url,
+ "aud": "example-client",
+ "sub": sub,
+ "name": name,
+ "iat": int(timezone.now().timestamp()),
+ "exp": int(timezone.now().timestamp()) + 60,
+ "nonce": params["nonce"][0],
+ }
+ token_response.update(
+ {
+ "access_token": "example-access-token",
+ "token_type": "Bearer",
+ "id_token": jwt.encode(claims, private_key, algorithm="RS256", headers={"kid": "example-key"}),
+ }
+ )
+ return self.client.get("/complete/oidc/", {"state": params["state"][0], "code": "example-code"})
+
+ def test_oidc_login_completes_without_storing_tokens(self):
+ self.user.email = "[email protected]"
+ self.user.save()
+ self.client.logout()
+
+ response = self._complete_oidc_login("[email protected]")
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(self.client.session["_auth_user_id"], str(self.user.pk))
+ self.assertEqual(response.cookies["ph_last_login_method"].value, "oidc")
+ social_auth = UserSocialAuth.objects.get(user=self.user, provider="oidc")
+ self.assertEqual(social_auth.uid, f"{self.config.oidc_issuer_url}:example-user")
+ self.assertEqual(social_auth.extra_data, {})
+
+ def test_oidc_jit_provisioning_creates_user_on_verified_domain(self):
+ self.domain.jit_provisioning_enabled = True
+ self.domain.save()
+ self.client.logout()
+ user_count = User.objects.count()
+
+ response = self._complete_oidc_login("[email protected]", sub="new-user", name="New Member")
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(User.objects.count(), user_count + 1)
+ user = cast(User, User.objects.get(email="[email protected]"))
+ self.assertEqual(user.first_name, "New Member")
+ self.assertEqual(user.organization, self.organization)
+ self.assertEqual(user.team, self.team)
+ self.assertEqual(
+ cast(OrganizationMembership, user.organization_memberships.get()).level,
+ OrganizationMembership.Level.MEMBER,
+ )
+ self.assertEqual(self.client.session["_auth_user_id"], str(user.pk))
+ social_auth = UserSocialAuth.objects.get(user=user, provider="oidc")
+ self.assertEqual(social_auth.uid, f"{self.config.oidc_issuer_url}:new-user")
+
+ def test_oidc_jit_provisioning_disabled_does_not_provision_user(self):
+ self.assertFalse(self.domain.jit_provisioning_enabled)
+ self.client.logout()
+ user_count = User.objects.count()
+
+ response = self._complete_oidc_login("[email protected]", sub="new-user", name="New Member")
+
+ self.assertEqual(response.status_code, 302)
+ self.assertEqual(User.objects.count(), user_count)
+ self.assertFalse(User.objects.filter(email="[email protected]").exists())
+ self.assertNotIn("_auth_user_id", self.client.session)
+
+ def test_oidc_redirect_uses_pkce_and_tenant_client(self):
+ with patch.object(
+ self.backend,
+ "get_json",
+ return_value={
+ "issuer": self.config.oidc_issuer_url,
+ "authorization_endpoint": "https://idp.example.com/authorize",
+ "token_endpoint": "https://idp.example.com/token",
+ "jwks_uri": "https://idp.example.com/keys",
+ },
+ ):
+ params = parse_qs(urlparse(self.backend.auth_url()).query)
+ self.assertEqual(params["client_id"], ["example-client"])
+ self.assertEqual(params["code_challenge_method"], ["S256"])
+ self.assertEqual(params["scope"], ["openid profile email"])
+ self.assertTrue(params["state"])
+ self.assertTrue(params["nonce"])
+
+ def test_oidc_rejects_another_domain(self):
+ self.backend.id_token = cast(Any, {"sub": "example-user"})
+ with patch(
+ "posthog.api.oidc.OpenIdConnectAuth.user_data",
+ return_value={
+ "sub": "example-user",
+ "email": "[email protected]",
+ "email_verified": True,
+ },
+ ):
+ with self.assertRaises(AuthFailed):
+ self.backend.user_data("example-access-token")
+
+ @parameterized.expand([("missing", None), ("false", False), ("string", "true")])
+ def test_oidc_requires_verified_email_from_userinfo(self, _name, email_verified):
+ self.backend.id_token = cast(Any, {"sub": "example-user"})
+ userinfo: dict[str, Any] = {"sub": "example-user", "email": "[email protected]"}
+ if email_verified is not None:
+ userinfo["email_verified"] = email_verified
+ with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
+ with self.assertRaises(AuthFailed):
+ self.backend.user_data("example-access-token")
+
+ def test_oidc_accepts_verified_email_from_userinfo(self):
+ self.backend.id_token = cast(Any, {"sub": "example-user"})
+ userinfo = {
+ "sub": "example-user",
+ "email": "[email protected]",
+ "email_verified": True,
+ }
+ with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
+ response = self.backend.user_data("example-access-token")
+ self.assertEqual(self.backend.get_user_id({}, response), f"{self.config.oidc_issuer_url}:example-user")
+ self.assertEqual(self.backend.extra_data(None, "uid", response, {}), {})
+
+ def test_oidc_get_user_id_normalizes_issuer_url(self):
+ self.backend.identity_provider_config = self.config
+ self.config.oidc_issuer_url = "https://idp.example.com/"
+
+ self.assertEqual(self.backend.get_user_id({}, {"sub": "example-user"}), "https://idp.example.com:example-user")
+
+ def test_oidc_get_user_id_rejects_identifiers_longer_than_255_characters(self):
+ self.backend.identity_provider_config = self.config
+ issuer = self.config.oidc_issuer_url.rstrip("/")
+ subject = "s" * (256 - len(f"{issuer}:"))
+
+ with self.assertRaises(AuthFailed):
+ self.backend.get_user_id({}, {"sub": subject})
+
+ def test_oidc_rejects_userinfo_for_another_subject(self):
+ self.backend.id_token = cast(Any, {"sub": "example-user"})
+ userinfo = {
+ "sub": "other-user",
+ "email": "[email protected]",
+ "email_verified": True,
+ }
+ with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
+ with self.assertRaises(AuthFailed):
+ self.backend.user_data("example-access-token")
+
+ def test_oidc_rejects_removed_entitlement(self):
+ self.organization.available_product_features = []
+ self.organization.save()
+ with self.assertRaises(AuthFailed):
+ self.backend.get_key_and_secret()
+
+ def test_oidc_rejects_unverified_domain(self):
+ self.domain.verified_at = None
+ self.domain.save()
+ with self.assertRaises(AuthFailed):
+ self.backend.auth_url()
+
+ def test_oidc_rejects_overlapping_configurations(self):
+ self.config.pk = uuid.uuid4()
+ self.config.saml_relay_state = str(uuid.uuid4())
+ self.config.scim_slug = str(uuid.uuid4())
+ self.config.save()
+ with self.assertRaises(AuthFailed):
+ self.backend.auth_url()
+
+ @parameterized.expand(
+ [
+ ("mismatch", "https://idp.example.com", "https://other.example.com", False),
+ ("configured_trailing_slash", "https://idp.example.com/", "https://idp.example.com", True),
+ ("discovered_trailing_slash", "https://idp.example.com", "https://idp.example.com/", True),
+ ]
+ )
+ def test_oidc_checks_discovery_issuer(self, _name, configured_issuer, discovered_issuer, accepted):
+ self.config.oidc_issuer_url = configured_issuer
+ self.config.save()
+
+ with patch.object(
+ self.backend,
+ "get_json",
+ return_value={
+ "issuer": discovered_issuer,
+ "authorization_endpoint": "https://idp.example.com/authorize",
+ "token_endpoint": "https://idp.example.com/token",
+ "jwks_uri": "https://idp.example.com/keys",
+ },
+ ):
+ if accepted:
+ self.assertEqual(self.backend.oidc_config()["issuer"], discovered_issuer)
+ else:
+ with self.assertRaises(AuthFailed):
+ self.backend.oidc_config()
+
+ def test_oidc_does_not_share_discovery_between_tenants(self):
+ other_backend = MultitenantOIDCAuth(self.backend.strategy, self.backend.redirect_uri)
+ other_config = MagicMock(oidc_issuer_url="https://other.example.com")
+ other_backend.identity_provider_config = other_config
+ for backend, issuer in [
+ (self.backend, self.config.oidc_issuer_url),
+ (other_backend, other_config.oidc_issuer_url),
+ ]:
+ with patch.object(
+ backend,
+ "get_json",
+ return_value={
+ "issuer": issuer,
+ "authorization_endpoint": f"{issuer}/authorize",
+ "token_endpoint": f"{issuer}/token",
+ "jwks_uri": f"{issuer}/keys",
+ },
+ ) as get_json:
+ self.assertEqual(backend.oidc_config()["issuer"], issuer)
+ get_json.assert_called_once_with(f"{issuer}/.well-known/openid-configuration")
+
+ def test_oidc_enforcement_checks_entitlement(self):
+ self.domain.sso_enforcement = "oidc"
+ self.domain.save()
+ self.assertEqual(OrganizationDomain.objects.get_sso_enforcement_for_email_address("[email protected]"), "oidc")
+ self.organization.available_product_features = [{"key": AvailableFeature.SSO_ENFORCEMENT}]
+ self.organization.save()
+ self.assertIsNone(OrganizationDomain.objects.get_sso_enforcement_for_email_address("[email protected]"))
+
+ def test_oidc_precheck_requires_configured_and_licensed_provider(self):
+ self.domain.sso_enforcement = "oidc"
+ self.domain.save()
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(response.json()["sso_enforcement"], "oidc")
+ self.assertTrue(response.json()["oidc_available"])
+
+ self.config.oidc_credentials = {}
+ self.config.save()
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertIsNone(response.json()["sso_enforcement"])
+ self.assertFalse(response.json().get("oidc_available", False))
+
+
class TestEELoginPrecheckAPI(APILicensedTest):
CONFIG_AUTO_LOGIN = False
@@ -74,6 +452,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
{
"sso_enforcement": "google-oauth2",
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -98,6 +477,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -121,6 +501,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
{
"sso_enforcement": "github",
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -145,6 +526,7 @@ class TestEELoginPrecheckAPI(APILicensedTest):
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -359,6 +741,45 @@ class TestEEAuthenticationAPI(APILicensedTest):
self.assertIn("accounts.google.com", response.headers["Location"])
self.assertEqual(self.client.session.session_key, session_key_before)
+ @patch("posthog.api.authentication.auth", return_value=redirect("/"))
+ def test_connect_from_oidc_flushes_the_authenticated_session(self, _mock_auth):
+ response = self.client.get("/login/oidc/?connect_from=posthog_code")
+
+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)
+ self.assertNotIn("_auth_user_id", self.client.session)
+
+ @parameterized.expand([("oidc",), ("github",)])
+ def test_authenticated_session_cannot_attach_a_different_social_identity(self, backend_name):
+ request = RequestFactory().get("/complete/oidc/")
+ request.session = self.client.session
+ request.user = self.user
+ strategy = load_strategy(request)
+
+ with self.assertRaises(AuthFailed):
+ social_identity_matches_session(
+ strategy,
+ backend=SimpleNamespace(name=backend_name),
+ details={"email": "[email protected]"},
+ user=None,
+ )
+
+ def test_github_account_link_allows_a_different_identity_email(self):
+ session = self.client.session
+ session["next"] = "/account-connected/github-login?provider=github&connect_from=posthog_code"
+ session.save()
+
+ request = RequestFactory().get("/complete/github/")
+ request.session = session
+ request.user = self.user
+ strategy = load_strategy(request)
+
+ social_identity_matches_session(
+ strategy,
+ backend=SimpleNamespace(name="github"),
+ details={"email": "[email protected]"},
+ user=self.user,
+ )
+
@parameterized.expand(
[
("plain_path", "/settings/user", "/settings/user?error_code=improperly_configured_sso"),
@@ -620,6 +1041,7 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
{
"sso_enforcement": None,
"saml_available": True,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -1144,6 +1566,11 @@ YotAcSbU3p5bzd11wpyebYHB"""
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_saml_can_be_enforced(self):
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.SAML, "name": AvailableFeature.SAML},
+ {"key": AvailableFeature.SSO_ENFORCEMENT, "name": AvailableFeature.SSO_ENFORCEMENT},
+ ]
+ self.organization.save()
User.objects.create_and_join(
organization=self.organization,
@@ -1184,6 +1611,25 @@ YotAcSbU3p5bzd11wpyebYHB"""
{
"sso_enforcement": "saml",
"saml_available": True,
+ "oidc_available": False,
+ "webauthn_credentials": [],
+ "password_login_available": True,
+ "social_providers": [],
+ },
+ )
+
+ config = self.organization_domain.saml_identity_provider_configs.first()
+ assert config is not None
+ config.saml_x509_cert = ""
+ config.save()
+
+ response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
+ self.assertEqual(
+ response.json(),
+ {
+ "sso_enforcement": None,
+ "saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -1206,6 +1652,7 @@ YotAcSbU3p5bzd11wpyebYHB"""
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -1426,12 +1873,21 @@ class TestSSOEnforcement(APILicensedTest):
from ee.api.authentication import social_auth_allowed
# Create domain with SAML enforcement
- OrganizationDomain.objects.create(
+ domain = OrganizationDomain.objects.create(
domain="testdomain.com",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="saml",
)
+ config = IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="saml",
+ domain_scope="all",
+ saml_entity_id="https://idp.example.com",
+ saml_acs_url="https://idp.example.com/saml",
+ saml_x509_cert="test-certificate",
+ )
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
# Test that Google OAuth2 is blocked
with self.assertRaises(AuthFailed) as context:
diff --git a/ee/models/license.py b/ee/models/license.py
index 1a223e6af19c..26ca91ee26f8 100644
--- a/ee/models/license.py
+++ b/ee/models/license.py
@@ -76,6 +76,7 @@ class License(models.Model):
*SCALE_FEATURES,
AvailableFeature.ACCESS_CONTROL,
AvailableFeature.SAML,
+ AvailableFeature.OIDC,
AvailableFeature.SCIM,
AvailableFeature.SSO_ENFORCEMENT,
AvailableFeature.ROLE_BASED_ACCESS,
diff --git a/ee/settings.py b/ee/settings.py
index a9969b3aa0e9..765ed4a99c2e 100644
--- a/ee/settings.py
+++ b/ee/settings.py
@@ -12,6 +12,7 @@ from posthog.utils import str_to_bool
AUTHENTICATION_BACKENDS = [
*AUTHENTICATION_BACKENDS,
"ee.api.authentication.MultitenantSAMLAuth",
+ "posthog.api.oidc.MultitenantOIDCAuth",
"ee.api.authentication.CustomGoogleOAuth2",
]
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index de618540c549..70e255d51a6b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2109,9 +2109,9 @@ snapshots:
components-search--product-recents-and-starred--light:
hash: v1.k794b7964.419cabcff30a22d68b283cf59562b74ca2d4910552fc4240e95b856303622508.0xCO-YA2i8xkqSjPXRWXjmLuVEiiP11XfIC6v9y77yU
components-search--searching--dark:
- hash: v1.k794b7964.5d20a057f1b889c1d59cdfa49b54a3e89b91963cbee7f1fd288329d4f7ed1a10.s2FVUEYglLo0AxHCVr_IiUgI-tXpjNyDcbcp2JyuwYc
+ hash: v1.k794b7964.79cc43d6523611f3130b2c12fcc4cd29d765ff55983532f2b6b05a965879cb34.RZgOxgnzKDx6FomvNdIwTwxP43EQRgYUqlSn-F3rdRQ
components-search--searching--light:
- hash: v1.k794b7964.63afc23a6c49bdb56fee0edd18ed0cf565c94163320bb8faa762e025eb4618d5.eM5g4I0s072e_f1q96pZZVQhD1FtxoWbX7yfVXRbFgQ
+ hash: v1.k794b7964.cbcb7b6bf2df9986de6b5dae57696311c3b4b724b3b50f2ac8cff735bd17ad4f._ERsDMH-NJwBiwLZJv5zhZDCQN2bO4dkoiHwN2iJssc
components-sentencelist--full-sentence--dark:
hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxk
components-sentencelist--full-sentence--light:
@@ -9745,21 +9745,21 @@ snapshots:
scenes-app-settings-authentication-domains--boost-needs-upgrade--light:
hash: v1.k794b7964.f2e9c2eb21a4c51655c4a3a0aa51337cfb25a148b09b2b9e287eeb8e0cb108af.t6ZC79QgERyt8zxKmk77gqilvhiKGt4Wpyo1eN3l0Fg
scenes-app-settings-authentication-domains--enterprise-mixed--dark:
- hash: v1.k794b7964.108c87c596109921b63f0a0d31a15f573332b30f0dffd7cd6188c0122d7f710f.cFlzhGvQoqCOJL5vynqvLCJZbE9MXFyrK6L6AgCJWvA
+ hash: v1.k794b7964.29b5d74e6c842e45ed50d27f43c8aa4eca81da6155f3f7c47d55cda49b4a31c4.Nr1VS0htNKO8q9N6g6feUHg-s2oHxRh2v-P9KF1k3Co
scenes-app-settings-authentication-domains--enterprise-mixed--light:
- hash: v1.k794b7964.40932ded575174a10f507abcd661f02ef7bf721c5546b00f9614f6bcf7063f58.NDMSU-rKHfmmwNCmAyRzPPRKyfMl2M7_PfL9hcZvDSY
+ hash: v1.k794b7964.a662c53a2b569f23d0c1119e129da118d3ac309c06c6ec31315f811b7f646615.Ejtgq-DqGss8qha3sMFRqf5XDrKxDOBYPPtMFIpNyWI
scenes-app-settings-authentication-domains--enterprise-redesigned--dark:
- hash: v1.k794b7964.df660406aea718155486396c68f239019f453c2b977f56cce869a70a0036a35c.ULjaVx4orwIKBZY26gzI_GIjsM9VkSV_qIG54K36p0o
+ hash: v1.k794b7964.7bbc9841967b3a1a89e6d0b6895d67555b9cbdb1f821809b5aa4953892965653.7Ni7P-r3A3np0WVmHUEfuMvIeIdBZPsk-vuvlMKjHDU
scenes-app-settings-authentication-domains--enterprise-redesigned--light:
- hash: v1.k794b7964.502a1929ec6716472aeb362116ba2a412df0a07e481b6ea77b2e0cc1017f08a4.yKpG2G2VpzTLVsGPxYuemYJB6ca-cQbD-FLmsDx4RTE
+ hash: v1.k794b7964.862f5f3d2d2ac5579c4a354fb8ffcbb9b2e7d27f51de1f3c4c21d48b4059aad1.W3D0FxCkBGmdMRaB9mAiUwW-FrOSznhT1fVneRmCGlc
scenes-app-settings-authentication-domains--enterprise-redesigned-not-configured--dark:
- hash: v1.k794b7964.2fdc9a20542dea412ee10393c75a2039283875f7e959f0f2de01c11a45e98750.0lydVdG76e3mbLl2ts4aLlgp0nW3LvB-fh0wBuHHqI8
+ hash: v1.k794b7964.55cb948e6ccd9a4ef9df0e72254b9dac133526777b773056a5f47f6df3219be8.MlTKLoyY4ZL9nbFc3UTmHHYdIl_LhtrBj30stKELmVM
scenes-app-settings-authentication-domains--enterprise-redesigned-not-configured--light:
- hash: v1.k794b7964.f6fbf0d09cd3f8e831fe9be8d1c582a79467f94b0791356bfc54a10a58c594bc.HCC-fvhlRh7md1tIrNnv6Ztb3ney24usQOnx65ooIDM
+ hash: v1.k794b7964.efdb62154451089653a674333fb0b6e5ce707a2773f365fbf2083d637e387c19.yefuW3p2kzJJ6bSkzsZW41jZSMycfDw0sQw2-o1FSCA
scenes-app-settings-authentication-domains--enterprise-redesigned-partially-configured--dark:
- hash: v1.k794b7964.b68b01b6d3df1e6eff516d92a30d184deb49be7e4394f6771d436667db42b617.Bc0f_07tsO5JlXoJuZUp66CA9vbk15OX6XzUXYomfrg
+ hash: v1.k794b7964.fa2cdf6ae415b28867b3695d399c1313ccf4f2e56ea08feeba1ba52a59c2c562.lIK3vCs2PRQ1396XpGCaIxzJievZ2Abxny-Ig01PW90
scenes-app-settings-authentication-domains--enterprise-redesigned-partially-configured--light:
- hash: v1.k794b7964.5bc1ae2b732b188937b7b58e210db27b5023d5acb4265a95d533b910e11ad91c.nxwI2Vdgl0XgOlNRuOga2Heritqq5eXSoTOzC6xR_r0
+ hash: v1.k794b7964.e42ca2f600dc13e53bf7d92267675d0ddd103ae91fbf24215f0b3a73dc2d4bb5.He1Yz_SvY2rkBosHXmrJLz-mowhnW615huwujDccYew
scenes-app-settings-authentication-domains--no-domains--dark:
hash: v1.k794b7964.365ab75f8244465afcf6c780d914f58714c3c2a45327df24e6233e22fcfd8219.PNbvIBWSnszxnnRuPNfZ-keyPcVA4LowiNnzMX0iwJ8
scenes-app-settings-authentication-domains--no-domains--light:
@@ -9769,9 +9769,9 @@ snapshots:
scenes-app-settings-authentication-domains--one-unverified-domain--light:
hash: v1.k794b7964.c8a0f7769778cddceb7039294f329579d3cbd4cebf8213244bb587e31b3594e7.M2L5rnKZhsweIrTL7P1WVrsy7iU_rXs5cgCg7OVX45c
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--dark:
- hash: v1.k794b7964.921c4829637465833f4ba5097f830a98f4a1a876df15bd8bc42985ea7732735f.aEP0S3QLtuDeX0No-xM4PvLEpMrChH0-TRfx-vjm-CI
+ hash: v1.k794b7964.d1bb4f98f20cf9af1d35f25b57691c326458ff4d391e0cb5f3e282ce73c40d14.A9fC2ufXK94hdriXY-DYnLYYq5jEbebx9SPWz6PrmbE
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--light:
- hash: v1.k794b7964.87f701cbae0118c13f2bc5d4ee5d2ba6b325a8bf40d1500e045a89894f6c2a8d.BPLSU7sY_VBMrCQeaUrvDKKcJhsk81kfy7gBaG9KNpI
+ hash: v1.k794b7964.51fd93d8358151ef04e8aeaf79995d0fad5d400dc7c11bf60e6afe28a669f3b1.co3ycYzfNxlUoUXBpcPaiaC8OCjGnnKGsFSckVSRnmE
scenes-app-settings-environment--settings-environment-access-control--dark:
hash: v1.k794b7964.ac9d676833fd6c23fa7bbb9d03a87b8268b01b3e0cc9134b5da51ad26b1b878f.vkMrX_g4dXSDgQzzWFCZKO5cXss4NyoBhQz6VNNBam4
scenes-app-settings-environment--settings-environment-access-control--light:
@@ -9864,6 +9864,14 @@ snapshots:
hash: v1.k794b7964.eb79f313f1c5dbf00e0689c0146e5116234b52f8835fd7d5c3fe2f9b41cf1bbb.2ixJGP2YQe4fQy9SW5hHOT5Kwam27dvHJgJps1yZ3h8
scenes-app-settings-environment--settings-environment-web-analytics--light:
hash: v1.k794b7964.71f6b9c1343a9bb2d8ec78dfebae8d7d9845882353fd2f03f63d45c5ce238431.gnx48GKk7hyfbiZTB-hdcMC4K5dpCekR-NpE7kD7sVY
+ scenes-app-settings-identity-provider-configuration--oidc--dark:
+ hash: v1.k794b7964.1177527533a6ec000b396e1ee39627722226aed5cbab11759198dbbc2d72dcb3.NqKVUNSdSz-yE-r1M5EiEIaPRbQwBbyjCAf7rSSi9Do
+ scenes-app-settings-identity-provider-configuration--oidc--light:
+ hash: v1.k794b7964.03f83eaa239cca8bd544c4167ff98b23a743cfb93fcdbcd5c142a022fc971bff.QR0PdAe2fuikMbSryle5gPipwwtar2esbHh9WqWjxxo
+ scenes-app-settings-identity-provider-configuration--oidc-needs-upgrade--dark:
+ hash: v1.k794b7964.3af8810df7232e0e72b04e29e4447c5780b718c4b3a48c4d9a728840c3582148.bsgrR3LFg45idWxkLkaXPWfC2p6F1ONigq7VxiS-4qA
+ scenes-app-settings-identity-provider-configuration--oidc-needs-upgrade--light:
+ hash: v1.k794b7964.96dca624545b90ef9cd31db1b35f98707ba0ef975d8800b76c13b7869058c07a.DwbImDP0BFPZQvKry-89o5YQlP5bvEgf2thj0byen0Q
scenes-app-settings-identity-provider-configuration--saml--dark:
hash: v1.k794b7964.9c7b18a36dd0e40bbd6198cbdcb6e3f7fe0957980d7c08ebca6847f720e4c5de.evwCcy9zneH0QBvV8NHTwls4OeHWET-MvykMYrg_59A
scenes-app-settings-identity-provider-configuration--saml--light:
@@ -9885,9 +9893,9 @@ snapshots:
scenes-app-settings-identity-provider-configuration--xaa-needs-upgrade--light:
hash: v1.k794b7964.9d93b0682bf14e191da3fa9614a1500ec01fbe7a9c313680c5fa2d776ae65806.KFggaDLcSJvceGa1JimS0m5ayPo6m_OtoH7_tzeqR-8
scenes-app-settings-organization--settings-organization-authentication--dark:
- hash: v1.k794b7964.a92c53208573be95eb2d121a63c97da2e0cb42acb4e1b3e91d84f84f66b1c961.WPCnXrULsBNC4Eg9DhVZ2_2P5WgGl5yJ0DKxCMznCYo
+ hash: v1.k794b7964.b8cfa5108a256162d0a4deab868eaaf409a003f261dea2ad49609b3b9f47d086.7qbgd4rSxRKso197SX48SwrwDapvKxZ5t9chxqTi9sY
scenes-app-settings-organization--settings-organization-authentication--light:
- hash: v1.k794b7964.96a9e91d0b28deb7de9118d277d5909a9e155bb1685106d8d9659bfbbd895b97.PPexQj6we-P3SwhqOr9hULNB6P-kIdD9d3qnobJr_SI
+ hash: v1.k794b7964.e70e1b180523270a9f7c1fb57e874c4de1d93142e9adbb9bc18b52e189557741.RMgUyCoFhfshhm4TAQJMt-CuYUTh6_MEz14bnP7dU1k
scenes-app-settings-organization--settings-organization-billing--dark:
hash: v1.k794b7964.586910a373b9a9cf63d114f527d0bb8580033d25a81be6f830e07bf244a7c316.ddsAKbm-zY3SbnudYISUg1QKtsIxUJxu4nCHOlMx4bo
scenes-app-settings-organization--settings-organization-billing--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f0a041cc196b..b096948a8d35 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -236,6 +236,7 @@ export const DomainScopeEnumApi = {
/**
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa
*/
@@ -243,6 +244,7 @@ export type ConfigScopeEnumApi = (typeof ConfigScopeEnumApi)[keyof typeof Config
export const ConfigScopeEnumApi = {
Saml: 'saml',
+ Oidc: 'oidc',
Scim: 'scim',
Xaa: 'xaa',
} as const
@@ -262,6 +264,7 @@ export interface IdentityProviderConfigApi {
/** Feature configured by this identity provider configuration.
*
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa */
config_scope?: ConfigScopeEnumApi | BlankEnumApi | null
@@ -271,6 +274,22 @@ export interface IdentityProviderConfigApi {
readonly updated_at: string
/** Whether SAML is fully configured on this config. */
readonly has_saml: boolean
+ /** Whether OIDC has an issuer, client ID, and client secret. */
+ readonly has_oidc: boolean
+ /** Whether an encrypted OIDC client secret is saved. */
+ readonly has_oidc_client_secret: boolean
+ /** HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document. */
+ oidc_issuer_url?: string
+ /**
+ * Client ID of the organization's OIDC application.
+ * @maxLength 512
+ */
+ oidc_client_id?: string
+ /**
+ * OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.
+ * @maxLength 4096
+ */
+ oidc_client_secret?: string
/** Stable UUID sent as SAML RelayState to route authentication responses to this IdP configuration. */
readonly saml_relay_state: string
/**
@@ -346,6 +365,7 @@ export interface PatchedIdentityProviderConfigApi {
/** Feature configured by this identity provider configuration.
*
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa */
config_scope?: ConfigScopeEnumApi | BlankEnumApi | null
@@ -355,6 +375,22 @@ export interface PatchedIdentityProviderConfigApi {
readonly updated_at?: string
/** Whether SAML is fully configured on this config. */
readonly has_saml?: boolean
+ /** Whether OIDC has an issuer, client ID, and client secret. */
+ readonly has_oidc?: boolean
+ /** Whether an encrypted OIDC client secret is saved. */
+ readonly has_oidc_client_secret?: boolean
+ /** HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document. */
+ oidc_issuer_url?: string
+ /**
+ * Client ID of the organization's OIDC application.
+ * @maxLength 512
+ */
+ oidc_client_id?: string
+ /**
+ * OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.
+ * @maxLength 4096
+ */
+ oidc_client_secret?: string
/** Stable UUID sent as SAML RelayState to route authentication responses to this IdP configuration. */
readonly saml_relay_state?: string
/**
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 1b2cc3afccc2..c99988d3d029 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -120,6 +120,14 @@ export const DomainsVerifyCreateBody = /* @__PURE__ */ zod.object({
export const identityProviderConfigsCreateBodyNameMax = 255
+export const identityProviderConfigsCreateBodyOidcIssuerUrlOneMax = 512
+
+export const identityProviderConfigsCreateBodyOidcIssuerUrlTwoMax = 0
+
+export const identityProviderConfigsCreateBodyOidcClientIdMax = 512
+
+export const identityProviderConfigsCreateBodyOidcClientSecretMax = 4096
+
export const identityProviderConfigsCreateBodySamlEntityIdMax = 512
export const identityProviderConfigsCreateBodySamlAcsUrlMax = 512
@@ -148,18 +156,39 @@ export const IdentityProviderConfigsCreateBody = /* @__PURE__ */ zod.object({
),
config_scope: zod
.union([
- zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod
+ .enum(['saml', 'oidc', 'scim', 'xaa'])
+ .describe('\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'),
zod.enum(['']),
zod.null(),
])
.optional()
.describe(
- 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'
),
organization_domain_ids: zod
.array(zod.uuid())
.optional()
.describe('Organization domain IDs that this identity provider configuration applies to.'),
+ oidc_issuer_url: zod
+ .union([
+ zod.url().max(identityProviderConfigsCreateBodyOidcIssuerUrlOneMax),
+ zod.string().max(identityProviderConfigsCreateBodyOidcIssuerUrlTwoMax),
+ ])
+ .optional()
+ .describe('HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document.'),
+ oidc_client_id: zod
+ .string()
+ .max(identityProviderConfigsCreateBodyOidcClientIdMax)
+ .optional()
+ .describe("Client ID of the organization's OIDC application."),
+ oidc_client_secret: zod
+ .string()
+ .max(identityProviderConfigsCreateBodyOidcClientSecretMax)
+ .optional()
+ .describe(
+ 'OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.'
+ ),
saml_entity_id: zod
.string()
.max(identityProviderConfigsCreateBodySamlEntityIdMax)
@@ -195,6 +224,14 @@ export const IdentityProviderConfigsCreateBody = /* @__PURE__ */ zod.object({
export const identityProviderConfigsUpdateBodyNameMax = 255
+export const identityProviderConfigsUpdateBodyOidcIssuerUrlOneMax = 512
+
+export const identityProviderConfigsUpdateBodyOidcIssuerUrlTwoMax = 0
+
+export const identityProviderConfigsUpdateBodyOidcClientIdMax = 512
+
+export const identityProviderConfigsUpdateBodyOidcClientSecretMax = 4096
+
export const identityProviderConfigsUpdateBodySamlEntityIdMax = 512
export const identityProviderConfigsUpdateBodySamlAcsUrlMax = 512
@@ -223,18 +260,39 @@ export const IdentityProviderConfigsUpdateBody = /* @__PURE__ */ zod.object({
),
config_scope: zod
.union([
- zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod
+ .enum(['saml', 'oidc', 'scim', 'xaa'])
+ .describe('\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'),
zod.enum(['']),
zod.null(),
])
.optional()
.describe(
- 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'
),
organization_domain_ids: zod
.array(zod.uuid())
.optional()
.describe('Organization domain IDs that this identity provider configuration applies to.'),
+ oidc_issuer_url: zod
+ .union([
+ zod.url().max(identityProviderConfigsUpdateBodyOidcIssuerUrlOneMax),
+ zod.string().max(identityProviderConfigsUpdateBodyOidcIssuerUrlTwoMax),
+ ])
+ .optional()
+ .describe('HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document.'),
+ oidc_client_id: zod
+ .string()
+ .max(identityProviderConfigsUpdateBodyOidcClientIdMax)
+ .optional()
+ .describe("Client ID of the organization's OIDC application."),
+ oidc_client_secret: zod
+ .string()
+ .max(identityProviderConfigsUpdateBodyOidcClientSecretMax)
+ .optional()
+ .describe(
+ 'OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.'
+ ),
saml_entity_id: zod
.string()
.max(identityProviderConfigsUpdateBodySamlEntityIdMax)
@@ -270,6 +328,14 @@ export const IdentityProviderConfigsUpdateBody = /* @__PURE__ */ zod.object({
export const identityProviderConfigsPartialUpdateBodyNameMax = 255
+export const identityProviderConfigsPartialUpdateBodyOidcIssuerUrlOneMax = 512
+
+export const identityProviderConfigsPartialUpdateBodyOidcIssuerUrlTwoMax = 0
+
+export const identityProviderConfigsPartialUpdateBodyOidcClientIdMax = 512
+
+export const identityProviderConfigsPartialUpdateBodyOidcClientSecretMax = 4096
+
export const identityProviderConfigsPartialUpdateBodySamlEntityIdMax = 512
export const identityProviderConfigsPartialUpdateBodySamlAcsUrlMax = 512
@@ -298,18 +364,39 @@ export const IdentityProviderConfigsPartialUpdateBody = /* @__PURE__ */ zod.obje
),
config_scope: zod
.union([
- zod.enum(['saml', 'scim', 'xaa']).describe('\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'),
+ zod
+ .enum(['saml', 'oidc', 'scim', 'xaa'])
+ .describe('\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'),
zod.enum(['']),
zod.null(),
])
.optional()
.describe(
- 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `scim` - Scim\n\* `xaa` - Xaa'
+ 'Feature configured by this identity provider configuration.\n\n\* `saml` - Saml\n\* `oidc` - Oidc\n\* `scim` - Scim\n\* `xaa` - Xaa'
),
organization_domain_ids: zod
.array(zod.uuid())
.optional()
.describe('Organization domain IDs that this identity provider configuration applies to.'),
+ oidc_issuer_url: zod
+ .union([
+ zod.url().max(identityProviderConfigsPartialUpdateBodyOidcIssuerUrlOneMax),
+ zod.string().max(identityProviderConfigsPartialUpdateBodyOidcIssuerUrlTwoMax),
+ ])
+ .optional()
+ .describe('HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document.'),
+ oidc_client_id: zod
+ .string()
+ .max(identityProviderConfigsPartialUpdateBodyOidcClientIdMax)
+ .optional()
+ .describe("Client ID of the organization's OIDC application."),
+ oidc_client_secret: zod
+ .string()
+ .max(identityProviderConfigsPartialUpdateBodyOidcClientSecretMax)
+ .optional()
+ .describe(
+ 'OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.'
+ ),
saml_entity_id: zod
.string()
.max(identityProviderConfigsPartialUpdateBodySamlEntityIdMax)
diff --git a/frontend/src/lib/components/SocialLoginButton/SocialLoginIcon.tsx b/frontend/src/lib/components/SocialLoginButton/SocialLoginIcon.tsx
index 937172b15966..8972b0868e48 100644
--- a/frontend/src/lib/components/SocialLoginButton/SocialLoginIcon.tsx
+++ b/frontend/src/lib/components/SocialLoginButton/SocialLoginIcon.tsx
@@ -17,7 +17,7 @@ export const SocialLoginIcon = ({
return <IconGithub {...props} />
} else if (provider === 'gitlab') {
return <IconGitlab {...props} />
- } else if (provider === 'saml') {
+ } else if (provider === 'saml' || provider === 'oidc') {
return <IconKey {...props} />
}
return null
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
index 1872188644e7..382d4f60a7f2 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx
@@ -147,6 +147,14 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {
extraQueryParams={extraQueryParams}
/>
) : null}
+ {precheckResponse?.oidc_available ? (
+ <SSOEnforcedLoginButton
+ provider="oidc"
+ email={user!.email}
+ size="medium"
+ extraQueryParams={extraQueryParams}
+ />
+ ) : null}
</div>
) : null}
{precheckResponseLoading && <SpinnerOverlay />}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b9f77b53ae7c..16c519290cab 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -632,6 +632,7 @@ export const SSO_PROVIDER_NAMES: Record<SSOProvider, string> = {
github: 'GitHub',
gitlab: 'GitLab',
saml: 'Single sign-on (SAML)',
+ oidc: 'Single sign-on (OIDC)',
}
export const DOMAIN_REGEX = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/
diff --git a/frontend/src/mocks/fixtures/_billing.tsx b/frontend/src/mocks/fixtures/_billing.tsx
index af41660d2451..b1b5106dc5e4 100644
--- a/frontend/src/mocks/fixtures/_billing.tsx
+++ b/frontend/src/mocks/fixtures/_billing.tsx
@@ -2968,6 +2968,14 @@ export const billingJson: BillingType = {
limit: null,
note: null,
},
+ {
+ key: 'oidc',
+ name: 'OIDC SSO',
+ description: "Allow your organization's users to log in with OpenID Connect.",
+ unit: null,
+ limit: null,
+ note: null,
+ },
{
key: '2fa',
name: '2FA',
@@ -3202,6 +3210,14 @@ export const billingJson: BillingType = {
icon_key: null,
type: null,
},
+ {
+ key: 'oidc',
+ name: 'OIDC SSO',
+ description: "Allow your organization's users to log in with OpenID Connect.",
+ images: null,
+ icon_key: null,
+ type: null,
+ },
{
key: 'sso_enforcement',
name: 'Enforce SSO login',
diff --git a/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx b/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
index 778aeccf909a..73fa2d0dd691 100644
--- a/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
+++ b/frontend/src/scenes/authentication/invite-signup/InviteSignupForm.tsx
@@ -267,6 +267,14 @@ function InviteNewUser({ invite }: { invite: PrevalidatedInvite }): JSX.Element
extraQueryParams={{ invite_id: invite.id }}
/>
)}
+ {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (
+ <SSOEnforcedLoginButton
+ provider="oidc"
+ email={invite.target_email}
+ actionText="Continue"
+ extraQueryParams={{ invite_id: invite.id }}
+ />
+ )}
</Form>
{!extraFieldsHidden && (
<InviteAlternativeLogins
diff --git a/frontend/src/scenes/authentication/login/LoginForm.tsx b/frontend/src/scenes/authentication/login/LoginForm.tsx
index 067ec3221343..8a3c5b755f22 100644
--- a/frontend/src/scenes/authentication/login/LoginForm.tsx
+++ b/frontend/src/scenes/authentication/login/LoginForm.tsx
@@ -418,6 +418,13 @@ export function LoginForm(): JSX.Element {
isLastUsed={lastLoginMethod === 'saml'}
/>
)}
+ {precheckResponse.oidc_available && !precheckResponse.sso_enforcement && (
+ <SSOEnforcedLoginButton
+ provider="oidc"
+ email={login.email}
+ isLastUsed={lastLoginMethod === 'oidc'}
+ />
+ )}
</Form>
)}
{/* Normally SAML replaces this row, but when the account has no password we need to
diff --git a/frontend/src/scenes/authentication/login/loginLogic.test.ts b/frontend/src/scenes/authentication/login/loginLogic.test.ts
index 8e7ced85b137..4d9a0df51d89 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.test.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.test.ts
@@ -382,6 +382,17 @@ describe('loginLogic', () => {
expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
})
+ it('offers OIDC for a passwordless account on an OIDC domain', async () => {
+ await precheck({
+ saml_available: false,
+ oidc_available: true,
+ password_login_available: false,
+ social_providers: [],
+ })
+ expect(logic.values.availableLoginMethods).toEqual(['oidc'])
+ expect(logic.values.hasNoConfiguredLoginMethod).toBe(false)
+ })
+
it('reports a dead end for a passwordless account with nothing else', async () => {
await precheck({ saml_available: false, password_login_available: false, social_providers: [] })
expect(logic.values.isPasswordLoginUnavailable).toBe(true)
diff --git a/frontend/src/scenes/authentication/login/loginLogic.ts b/frontend/src/scenes/authentication/login/loginLogic.ts
index 03e5ecf12fe2..f70d5fd992da 100644
--- a/frontend/src/scenes/authentication/login/loginLogic.ts
+++ b/frontend/src/scenes/authentication/login/loginLogic.ts
@@ -40,6 +40,7 @@ export interface AuthenticateResponseType {
export interface PrecheckResponseType {
sso_enforcement?: SSOProvider | null
saml_available: boolean
+ oidc_available?: boolean
status: 'pending' | 'completed'
webauthn_credentials?: PublicKeyCredentialDescriptorJSON[]
/**
@@ -541,6 +542,9 @@ export const loginLogic = kea<loginLogicType>([
if (precheckResponse.saml_available && !methods.includes('saml')) {
methods.push('saml')
}
+ if (precheckResponse.oidc_available && !methods.includes('oidc')) {
+ methods.push('oidc')
+ }
if (precheckResponse.webauthn_credentials?.length) {
methods.push('passkey')
}
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index c19566b033a4..745cdc07ece8 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -1977,6 +1977,14 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: 'SSO_SETTINGS_REDESIGN',
keywords: ['sso', 'saml', 'single sign-on', 'identity provider'],
},
+ {
+ id: 'oidc-configuration',
+ title: 'OIDC single sign-on',
+ description: 'Authenticate members through your identity provider with OpenID Connect (OIDC).',
+ component: <IdentityProviderFeatureSection configScope={ConfigScopeEnumApi.Oidc} />,
+ flag: 'SSO_SETTINGS_REDESIGN',
+ keywords: ['sso', 'oidc', 'openid connect', 'single sign-on', 'identity provider'],
+ },
{
id: 'scim-configuration',
title: 'SCIM provisioning',
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.stories.tsx b/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.stories.tsx
index 7307f5cd1895..7436192acb05 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.stories.tsx
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.stories.tsx
@@ -53,6 +53,7 @@ const USER_WITH_IDENTITY_PROVIDER_FEATURES = {
...MOCK_DEFAULT_ORGANIZATION,
available_product_features: [
AvailableFeature.SAML,
+ AvailableFeature.OIDC,
AvailableFeature.SCIM,
AvailableFeature.XAA_AUTHENTICATION,
].map((feature) => ({ key: feature, name: feature })),
@@ -136,6 +137,39 @@ const needsUpgradeDecorator = mswDecorator({
})
export const SAML: Story = { args: { configScope: ConfigScopeEnumApi.Saml } }
+export const OIDC: Story = {
+ args: { configScope: ConfigScopeEnumApi.Oidc },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/organizations/:id/identity_provider_configs/:configId': {
+ ...IDENTITY_PROVIDER_CONFIG,
+ config_scope: ConfigScopeEnumApi.Oidc,
+ oidc_issuer_url: 'https://idp.example.com',
+ oidc_client_id: 'example-client',
+ has_oidc: true,
+ has_oidc_client_secret: true,
+ },
+ },
+ }),
+ ],
+}
+export const OIDCNeedsUpgrade: Story = {
+ args: { configScope: ConfigScopeEnumApi.Oidc },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/users/@me': USER_WITHOUT_IDENTITY_PROVIDER_FEATURES,
+ '/api/organizations/:id/identity_provider_configs/:configId': {
+ ...IDENTITY_PROVIDER_CONFIG,
+ config_scope: ConfigScopeEnumApi.Oidc,
+ has_oidc: true,
+ has_oidc_client_secret: true,
+ },
+ },
+ }),
+ ],
+}
export const SAMLNeedsUpgrade: Story = {
args: { configScope: ConfigScopeEnumApi.Saml },
decorators: [needsUpgradeDecorator],
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.tsx b/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.tsx
index 56a27152ff6f..2b6fd877f68e 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.tsx
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/IdentityProviderConfigScene.tsx
@@ -23,6 +23,7 @@ import { identityProviderConfigLogic } from './identityProviderConfigLogic'
import type { IdentityProviderConfigLogicProps } from './identityProviderConfigLogic'
import { IDENTITY_PROVIDER_FEATURES, isIdentityProviderConfigScope } from './identityProviderConfigUtils'
import { IdentityProviderDomainScope } from './IdentityProviderDomainScope'
+import { OIDCConfigFields } from './OIDCConfigFields'
import { SAMLConfigFields } from './SAMLConfigFields'
import { SCIMConfigFields } from './SCIMConfigFields'
import { XAAConfigFields } from './XAAConfigFields'
@@ -66,6 +67,7 @@ export function IdentityProviderConfigScene(): JSX.Element | null {
openDeleteModal,
closeDeleteModal,
setDeleteConfirmation,
+ setIdentityProviderConfigFormValues,
} = useActions(identityProviderConfigLogic)
const { preflight } = useValues(preflightLogic)
const restrictionReason = useRestrictedArea({
@@ -153,6 +155,18 @@ export function IdentityProviderConfigScene(): JSX.Element | null {
disabled={isIdentityProviderConfigFormSubmitting}
onRegenerateToken={regenerateScimToken}
/>
+ ) : configScope === ConfigScopeEnumApi.Oidc ? (
+ <OIDCConfigFields
+ siteUrl={siteUrl}
+ hasClientSecret={Boolean(identityProviderConfig?.has_oidc_client_secret)}
+ clientSecretCleared={identityProviderConfigForm.oidc_client_secret_cleared}
+ onClearClientSecret={() => {
+ setIdentityProviderConfigFormValues({
+ oidc_client_secret: '',
+ oidc_client_secret_cleared: true,
+ })
+ }}
+ />
) : (
<XAAConfigFields isReady={Boolean(identityProviderConfigForm.id_jag_issuer_url)} />
)}
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/OIDCConfigFields.tsx b/frontend/src/scenes/settings/organization/IdentityProviderConfig/OIDCConfigFields.tsx
new file mode 100644
index 000000000000..cc4181a1be6c
--- /dev/null
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/OIDCConfigFields.tsx
@@ -0,0 +1,84 @@
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
+
+export function OIDCConfigFields({
+ siteUrl,
+ hasClientSecret,
+ clientSecretCleared,
+ onClearClientSecret,
+}: {
+ siteUrl: string
+ hasClientSecret: boolean
+ clientSecretCleared: boolean
+ onClearClientSecret: () => void
+}): JSX.Element {
+ return (
+ <div className="space-y-4">
+ <p>
+ Create an OpenID Connect application in your identity provider. Use the authorization code flow with
+ PKCE (S256), and sign ID tokens with RS256. Add this redirect URL to the application.
+ </p>
+ <LemonField label="Redirect URL" name="_oidc_redirect_url">
+ <CopyToClipboardInline>{`${siteUrl}/complete/oidc/`}</CopyToClipboardInline>
+ </LemonField>
+ <LemonField label="Issuer URL" name="oidc_issuer_url">
+ <LemonInput placeholder="https://idp.example.com" autoComplete="off" />
+ </LemonField>
+ <LemonField label="Client ID" name="oidc_client_id">
+ <LemonInput autoComplete="off" />
+ </LemonField>
+ <LemonField label="Client secret" name="oidc_client_secret">
+ {hasClientSecret && !clientSecretCleared ? (
+ <div className="space-y-3">
+ <p className="text-secondary mb-0">
+ A client secret is saved. You cannot view it after saving. Update it to enter a new client
+ secret.
+ </p>
+ <LemonButton
+ type="secondary"
+ onClick={onClearClientSecret}
+ data-attr="clear-oidc-client-secret"
+ >
+ Update client secret
+ </LemonButton>
+ </div>
+ ) : (
+ <LemonInput
+ type="password"
+ autoComplete="new-password"
+ className="ph-no-capture"
+ data-attr="oidc-client-secret"
+ />
+ )}
+ </LemonField>
+ <LemonBanner type="info">
+ <p>
+ In your identity provider, allow this OIDC application to request the <code>openid</code>,{' '}
+ <code>profile</code>, and <code>email</code> scopes. PostHog requests these scopes when a user signs
+ in.
+ </p>
+ <p>
+ PostHog reads the user's identity from the <code>userinfo</code> endpoint of your identity provider.
+ The response must include these claims:
+ </p>
+ <ul className="list-disc pl-4">
+ <li>
+ <code>sub</code>: a stable identifier for the user. It must match the <code>sub</code> claim in
+ the ID token.
+ </li>
+ <li>
+ <code>email</code>: the user's email address
+ </li>
+ <li>
+ <code>email_verified</code>: must be <code>true</code>. Sign-in fails if your identity provider
+ omits this claim, or sends <code>false</code> or the string <code>"true"</code>.
+ </li>
+ </ul>
+ <p>The email address must use a domain verified in this configuration.</p>
+ </LemonBanner>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.test.ts b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.test.ts
index c1fb5c86e125..a815b1337475 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.test.ts
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.test.ts
@@ -33,6 +33,8 @@ const CREATED_CONFIG: IdentityProviderConfigApi = {
created_at: '2026-08-01T00:00:00Z',
updated_at: '2026-08-01T00:00:00Z',
has_saml: true,
+ has_oidc: false,
+ has_oidc_client_secret: false,
saml_relay_state: '0198bbbb-0000-4000-8000-000000000001',
saml_entity_id: 'entity-id',
saml_acs_url: 'https://idp.example.com/sso',
@@ -44,6 +46,70 @@ const CREATED_CONFIG: IdentityProviderConfigApi = {
}
describe('identityProviderConfigLogic', () => {
+ it('saves OIDC settings and clears the secret from the form', async () => {
+ let requestBody: Record<string, unknown> | undefined
+ const oidcConfig = {
+ ...CREATED_CONFIG,
+ config_scope: ConfigScopeEnumApi.Oidc,
+ oidc_issuer_url: 'https://idp.example.com',
+ oidc_client_id: 'example-client',
+ has_oidc: true,
+ has_oidc_client_secret: true,
+ }
+ useMocks({
+ get: {
+ '/api/organizations/:organization/domains': { count: 0, next: null, previous: null, results: [] },
+ },
+ post: {
+ '/api/organizations/:organization/identity_provider_configs': async ({ request }) => {
+ requestBody = (await request.json()) as Record<string, unknown>
+ return [201, oidcConfig]
+ },
+ },
+ patch: {
+ '/api/organizations/:organization/identity_provider_configs/:configId': async ({ request }) => {
+ requestBody = (await request.json()) as Record<string, unknown>
+ return [200, oidcConfig]
+ },
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SSO_SETTINGS_REDESIGN], {
+ [FEATURE_FLAGS.SSO_SETTINGS_REDESIGN]: true,
+ })
+ const logic = identityProviderConfigLogic({ configScope: ConfigScopeEnumApi.Oidc, configId: 'new' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setIdentityProviderConfigFormValues({
+ oidc_issuer_url: ' https://idp.example.com ',
+ oidc_client_id: ' example-client ',
+ oidc_client_secret: 'example-secret',
+ })
+ logic.actions.submitIdentityProviderConfigForm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(requestBody).toMatchObject({
+ config_scope: ConfigScopeEnumApi.Oidc,
+ oidc_issuer_url: 'https://idp.example.com',
+ oidc_client_id: 'example-client',
+ oidc_client_secret: 'example-secret',
+ })
+ expect(logic.values.identityProviderConfigForm.oidc_client_secret).toBe('')
+ expect(logic.values.identityProviderConfigFormChanged).toBe(false)
+ logic.actions.setIdentityProviderConfigFormValues({ oidc_client_secret_cleared: true })
+ expect(logic.values.identityProviderConfigFormChanged).toBe(true)
+ logic.actions.submitIdentityProviderConfigForm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(requestBody).toMatchObject({ oidc_client_secret: '' })
+ logic.actions.setIdentityProviderConfigFormValues({ oidc_client_secret: '', oidc_client_secret_cleared: true })
+ logic.actions.setIdentityProviderConfigFormValues({ oidc_client_secret: 'rotated-secret' })
+ logic.actions.submitIdentityProviderConfigForm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(requestBody).toMatchObject({ oidc_client_secret: 'rotated-secret' })
+ logic.actions.setIdentityProviderConfigFormValues({ name: 'Updated provider' })
+ logic.actions.submitIdentityProviderConfigForm()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(requestBody).not.toHaveProperty('oidc_client_secret')
+ })
it('loads every page of organization domains', async () => {
const requestedOffsets: string[] = []
const firstPageDomains = Array.from({ length: 100 }, (_, index) => makeDomain(`domain-${index}`))
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.ts b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.ts
index f1d0bd64e31f..2a234cdb73e6 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.ts
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigLogic.ts
@@ -54,6 +54,10 @@ export interface IdentityProviderConfigForm {
saml_entity_id: string
saml_acs_url: string
saml_x509_cert: string
+ oidc_issuer_url: string
+ oidc_client_id: string
+ oidc_client_secret: string
+ oidc_client_secret_cleared: boolean
scim_enabled: boolean
id_jag_issuer_url: string
id_jag_jwks_url: string
@@ -68,6 +72,9 @@ type IdentityProviderConfigWritePayload = Pick<IdentityProviderConfigApi, 'domai
| 'saml_entity_id'
| 'saml_acs_url'
| 'saml_x509_cert'
+ | 'oidc_issuer_url'
+ | 'oidc_client_id'
+ | 'oidc_client_secret'
| 'scim_enabled'
| 'id_jag_issuer_url'
| 'id_jag_jwks_url'
@@ -85,6 +92,10 @@ const emptyIdentityProviderConfigForm = (): IdentityProviderConfigForm => ({
saml_entity_id: '',
saml_acs_url: '',
saml_x509_cert: '',
+ oidc_issuer_url: '',
+ oidc_client_id: '',
+ oidc_client_secret: '',
+ oidc_client_secret_cleared: false,
scim_enabled: false,
id_jag_issuer_url: '',
id_jag_jwks_url: '',
@@ -101,6 +112,10 @@ const formValuesFromConfig = (config: IdentityProviderConfigApi | null): Identit
saml_entity_id: config?.saml_entity_id ?? '',
saml_acs_url: config?.saml_acs_url ?? '',
saml_x509_cert: config?.saml_x509_cert ?? '',
+ oidc_issuer_url: config?.oidc_issuer_url ?? '',
+ oidc_client_id: config?.oidc_client_id ?? '',
+ oidc_client_secret: '',
+ oidc_client_secret_cleared: false,
scim_enabled: config?.scim_enabled ?? false,
id_jag_issuer_url: config?.id_jag_issuer_url ?? '',
id_jag_jwks_url: config?.id_jag_jwks_url ?? '',
@@ -131,6 +146,22 @@ const payloadFromForm = (
return { ...commonPayload, scim_enabled: formValues.scim_enabled }
}
+ if (configScope === ConfigScopeEnumApi.Oidc) {
+ return {
+ ...commonPayload,
+ oidc_issuer_url: formValues.oidc_issuer_url.trim(),
+ oidc_client_id: formValues.oidc_client_id.trim(),
+ // A typed secret must win over the cleared flag. The flag stays set once the admin opens the
+ // input, so testing it first would send an empty secret and delete the credential instead of
+ // rotating it.
+ ...(formValues.oidc_client_secret
+ ? { oidc_client_secret: formValues.oidc_client_secret }
+ : formValues.oidc_client_secret_cleared
+ ? { oidc_client_secret: '' }
+ : {}),
+ }
+ }
+
return {
...commonPayload,
id_jag_issuer_url: formValues.id_jag_issuer_url.trim() || null,
@@ -389,6 +420,12 @@ export const identityProviderConfigLogic = kea<identityProviderConfigLogicType>(
!isSecureUrl(formValues.id_jag_issuer_url)
? 'Enter a valid URL that starts with https://'
: undefined,
+ oidc_issuer_url:
+ props.configScope === ConfigScopeEnumApi.Oidc &&
+ formValues.oidc_issuer_url &&
+ !isSecureUrl(formValues.oidc_issuer_url)
+ ? 'Enter a valid URL that starts with https://'
+ : undefined,
id_jag_jwks_url:
props.configScope === ConfigScopeEnumApi.Xaa &&
formValues.id_jag_jwks_url &&
@@ -544,7 +581,10 @@ export const identityProviderConfigLogic = kea<identityProviderConfigLogicType>(
isConfigScopeValid: [
(selectors) => [selectors.identityProviderConfig, (_, props) => props.configScope],
(config: IdentityProviderConfigApi | null, configScope: ConfigScopeEnumApi | null): boolean =>
- !!configScope && (!config?.config_scope || config.config_scope === configScope),
+ !!configScope &&
+ (!config ||
+ config.config_scope === configScope ||
+ (configScope !== ConfigScopeEnumApi.Oidc && !config.config_scope)),
],
hasSamlDomainScopeConflict: [
(selectors) => [
@@ -628,7 +668,7 @@ export const identityProviderConfigLogic = kea<identityProviderConfigLogicType>(
return
}
- actions.resetIdentityProviderConfigForm(values.identityProviderConfigForm)
+ actions.resetIdentityProviderConfigForm(formValuesFromConfig(config))
if (props.configId === NEW_CONFIG_ID && config.id) {
// Adopt the saved config's URL so another save updates it instead of creating a duplicate.
router.actions.replace(urls.identityProviderConfig(props.configScope, config.id))
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.test.ts b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.test.ts
index 9c24bdb3bc61..df9ffe5ff57a 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.test.ts
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.test.ts
@@ -13,6 +13,8 @@ const makeConfig = (overrides: Partial<IdentityProviderConfigApi> = {}): Identit
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
has_saml: false,
+ has_oidc: false,
+ has_oidc_client_secret: false,
saml_relay_state: 'relay-state',
has_scim: false,
scim_base_url: 'https://example.com/scim/v2/config-id',
@@ -22,6 +24,20 @@ const makeConfig = (overrides: Partial<IdentityProviderConfigApi> = {}): Identit
})
describe('identityProviderConfigUtils', () => {
+ it('does not use legacy configurations for OIDC', () => {
+ expect(
+ getIdentityProviderConfigsForScope([makeConfig({ config_scope: null })], ConfigScopeEnumApi.Oidc)
+ ).toEqual([])
+ })
+
+ it.each([
+ [{}, 'not_configured'],
+ [{ oidc_issuer_url: 'https://idp.example.com' }, 'partially_configured'],
+ [{ has_oidc_client_secret: true }, 'partially_configured'],
+ [{ has_oidc: true }, 'configured'],
+ ] as const)('reports the OIDC configuration status for %j', (config, status) => {
+ expect(getIdentityProviderConfigStatus(makeConfig(config), ConfigScopeEnumApi.Oidc)).toBe(status)
+ })
it('returns every config for a feature while keeping legacy unscoped fallback behavior', () => {
const firstSamlConfig = makeConfig({ id: 'saml-1', config_scope: ConfigScopeEnumApi.Saml })
const secondSamlConfig = makeConfig({ id: 'saml-2', config_scope: ConfigScopeEnumApi.Saml })
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.ts b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.ts
index 19f119e720f6..64f9e8f5361f 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.ts
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigUtils.ts
@@ -16,6 +16,10 @@ const INCOMPLETE_STATUS_DESCRIPTIONS: Record<
ConfigScopeEnumApi,
Record<Exclude<IdentityProviderConfigStatus, 'configured'>, string>
> = {
+ [ConfigScopeEnumApi.Oidc]: {
+ not_configured: 'Add your identity provider details to enable OIDC single sign-on.',
+ partially_configured: 'Add the missing OIDC details to finish the configuration.',
+ },
[ConfigScopeEnumApi.Saml]: {
not_configured: 'Add your identity provider details to enable SAML single sign-on.',
partially_configured: 'Add the missing SAML details to finish the configuration.',
@@ -31,6 +35,12 @@ const INCOMPLETE_STATUS_DESCRIPTIONS: Record<
}
export const IDENTITY_PROVIDER_FEATURES: Record<ConfigScopeEnumApi, IdentityProviderFeatureDefinition> = {
+ [ConfigScopeEnumApi.Oidc]: {
+ name: 'OIDC',
+ title: 'OpenID Connect single sign-on',
+ description: 'Configure OpenID Connect authentication for your organization.',
+ availableFeature: AvailableFeature.OIDC,
+ },
[ConfigScopeEnumApi.Saml]: {
name: 'SAML',
title: 'SAML single sign-on',
@@ -89,7 +99,7 @@ export function getIdentityProviderConfigsForScope(
configScope: ConfigScopeEnumApi
): IdentityProviderConfigApi[] {
const scopedConfigs = configs.filter((config) => config.config_scope === configScope)
- return scopedConfigs.length > 0
+ return scopedConfigs.length > 0 || configScope === ConfigScopeEnumApi.Oidc
? scopedConfigs
: configs.filter((config) => config.config_scope == null || config.config_scope === '')
}
@@ -165,6 +175,15 @@ export function getIdentityProviderConfigStatus(
return 'not_configured'
}
+ if (configScope === ConfigScopeEnumApi.Oidc) {
+ if (config.has_oidc) {
+ return 'configured'
+ }
+ return config.oidc_issuer_url || config.oidc_client_id || config.has_oidc_client_secret
+ ? 'partially_configured'
+ : 'not_configured'
+ }
+
if (configScope === ConfigScopeEnumApi.Saml) {
if (config.has_saml) {
return 'configured'
diff --git a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigsLogic.test.ts b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigsLogic.test.ts
index cb86b1a96622..ecc7c9c5803d 100644
--- a/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigsLogic.test.ts
+++ b/frontend/src/scenes/settings/organization/IdentityProviderConfig/identityProviderConfigsLogic.test.ts
@@ -12,6 +12,8 @@ const makeConfig = (id: string): IdentityProviderConfigApi => ({
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
has_saml: true,
+ has_oidc: false,
+ has_oidc_client_secret: false,
saml_relay_state: 'relay-state',
has_scim: false,
scim_base_url: `https://example.com/scim/v2/${id}`,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.tsx
index 99641b38dccc..48bdcbda2544 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.tsx
@@ -13,6 +13,7 @@ export interface SSOSelectInterface {
loading: boolean
onChange: (value: SSOProvider | '') => void
samlAvailable: boolean
+ oidcAvailable?: boolean
disabledReason?: string | null
}
@@ -21,6 +22,7 @@ export function SSOSelect({
loading,
onChange,
samlAvailable,
+ oidcAvailable,
disabledReason,
}: SSOSelectInterface): JSX.Element | null {
const { preflight } = useValues(preflightLogic)
@@ -50,6 +52,15 @@ export function SSOSelect({
icon: <SocialLoginIcon provider="saml" className="w-4 h-4" />,
})
+ if (oidcAvailable !== undefined) {
+ options.push({
+ value: 'oidc',
+ label: SSO_PROVIDER_NAMES.oidc,
+ disabledReason: oidcAvailable ? undefined : 'This provider is not configured.',
+ icon: <SocialLoginIcon provider="oidc" className="w-4 h-4" />,
+ })
+ }
+
return (
<LemonSelect
value={value}
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
index 1581acec7733..aff7b19228e3 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
@@ -79,6 +79,7 @@ const ALL_FEATURES = [
AvailableFeature.AUTOMATIC_PROVISIONING,
AvailableFeature.SSO_ENFORCEMENT,
AvailableFeature.SAML,
+ AvailableFeature.OIDC,
AvailableFeature.SCIM,
AvailableFeature.XAA_AUTHENTICATION,
]
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
index c5379ebb9ee2..7679dfab8a85 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.tsx
@@ -109,6 +109,7 @@ function VerifiedDomainsTable(): JSX.Element {
updatingDomainLoading,
isSSOEnforcementAvailable,
isSAMLAvailable,
+ isOIDCAvailable,
isSCIMAvailable,
isXAAAuthenticationAvailable,
ownVerifiedDomain,
@@ -217,6 +218,11 @@ function VerifiedDomainsTable(): JSX.Element {
loading={updatingDomainLoading}
onChange={(val) => updateDomain({ id, sso_enforcement: val })}
samlAvailable={hasSaml}
+ oidcAvailable={Boolean(
+ isOIDCAvailable &&
+ getIdentityProviderConfigForDomain(identityProviderConfigs, id, ConfigScopeEnumApi.Oidc)
+ ?.has_oidc
+ )}
disabledReason={restrictionReason}
/>
)
@@ -236,6 +242,11 @@ function VerifiedDomainsTable(): JSX.Element {
id,
ConfigScopeEnumApi.Scim
)
+ const oidcConfig = getIdentityProviderConfigForDomain(
+ identityProviderConfigs,
+ id,
+ ConfigScopeEnumApi.Oidc
+ )
const idJagConfig = getIdentityProviderConfigForDomain(
identityProviderConfigs,
id,
@@ -277,6 +288,23 @@ function VerifiedDomainsTable(): JSX.Element {
)
}
+ badges.push(
+ <IntegrationBadge
+ key="oidc"
+ label="OIDC"
+ type={isOIDCAvailable && oidcConfig?.has_oidc ? 'success' : 'muted'}
+ icon={<IconLock />}
+ tooltip={
+ !isOIDCAvailable
+ ? 'Upgrade your plan to enable OIDC'
+ : oidcConfig?.has_oidc
+ ? 'OIDC is enabled'
+ : 'OIDC is not enabled'
+ }
+ to={!isOIDCAvailable ? billingLink : undefined}
+ />
+ )
+
if (!isSCIMAvailable) {
badges.push(
<IntegrationBadge
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
index 21be02095e74..17e466ed3512 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/__snapshots__/verifiedDomainsLogic.test.ts.snap
@@ -37,6 +37,7 @@ exports[`verifiedDomainsLogic values has proper defaults 1`] = `
"identityProviderConfigsLoading": false,
"isIdJagConfigSubmitting": false,
"isIdJagConfigValid": true,
+ "isOIDCAvailable": false,
"isSAMLAvailable": false,
"isSCIMAvailable": false,
"isSSOEnforcementAvailable": false,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
index d6a3b76947b9..3002d3c4ad9c 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.test.ts
@@ -144,6 +144,8 @@ describe('verifiedDomainsLogic', () => {
updated_at: '2024-01-01',
saml_relay_state: 'relay-state',
has_saml: false,
+ has_oidc: false,
+ has_oidc_client_secret: false,
has_scim: true,
scim_base_url: 'https://example.com/scim/v2/other',
scim_bearer_token: null,
@@ -157,6 +159,8 @@ describe('verifiedDomainsLogic', () => {
updated_at: '2024-01-01',
saml_relay_state: 'relay-state',
has_saml: true,
+ has_oidc: false,
+ has_oidc_client_secret: false,
has_scim: false,
scim_base_url: 'https://example.com/scim/v2/saml',
scim_bearer_token: null,
@@ -170,6 +174,8 @@ describe('verifiedDomainsLogic', () => {
updated_at: '2024-01-01',
saml_relay_state: 'relay-state',
has_saml: false,
+ has_oidc: false,
+ has_oidc_client_secret: false,
has_scim: true,
scim_base_url: 'https://example.com/scim/v2/scim',
scim_bearer_token: null,
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
index ff34cf55939a..452f568ab3ae 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/verifiedDomainsLogic.ts
@@ -148,6 +148,7 @@ export interface verifiedDomainsLogicValues {
identityProviderConfigsLoading: boolean
isIdJagConfigSubmitting: boolean
isIdJagConfigValid: boolean
+ isOIDCAvailable: boolean
isSAMLAvailable: boolean
isSCIMAvailable: boolean
isSSOEnforcementAvailable: boolean
@@ -713,6 +714,9 @@ export interface verifiedDomainsLogicMeta {
isSAMLAvailable: (
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
) => boolean
+ isOIDCAvailable: (
+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
+ ) => boolean
isSCIMAvailable: (
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
) => boolean
@@ -1143,6 +1147,11 @@ export const verifiedDomainsLogic = kea<verifiedDomainsLogicType>([
(hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
hasAvailableFeature(AvailableFeature.SAML),
],
+ isOIDCAvailable: [
+ () => [userLogic.selectors.hasAvailableFeature],
+ (hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
+ hasAvailableFeature(AvailableFeature.OIDC),
+ ],
isSCIMAvailable: [
() => [userLogic.selectors.hasAvailableFeature],
(hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean): boolean =>
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index a56ffaacf945..699450f10799 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -273,6 +273,7 @@ export type SettingId =
| 'revenue-analytics-filter-test-accounts'
| 'revenue-base-currency'
| 'saml-configuration'
+ | 'oidc-configuration'
| 'scim-configuration'
| 'session-join-mode'
| 'session-table-version'
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 392f88cb1f5d..3fbe71ca0d21 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -170,8 +170,10 @@ export const urls = {
aiHistory: (): string => '/ai/history',
settings: (section: SettingSectionId | SettingLevelId = 'project', setting?: SettingId): string =>
combineUrl(`/settings/${section}`, undefined, setting).url,
- identityProviderConfig: (feature: 'saml' | 'scim' | 'xaa' | ':feature', configId: string | ':configId'): string =>
- `/settings/organization-authentication/${feature}/${configId}`,
+ identityProviderConfig: (
+ feature: 'saml' | 'oidc' | 'scim' | 'xaa' | ':feature',
+ configId: string | ':configId'
+ ): string => `/settings/organization-authentication/${feature}/${configId}`,
featurePreview: (flagKey: string): string => combineUrl('/settings/user-feature-previews', {}, flagKey).url,
organizationCreationConfirm: (): string => '/organization/confirm-creation',
toolbarLaunch: (): string => '/toolbar',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 32212ffb9dd4..9e4e81b2753e 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -164,6 +164,7 @@ export enum AvailableFeature {
ROLE_BASED_ACCESS = 'role_based_access',
SOCIAL_SSO = 'social_sso',
SAML = 'saml',
+ OIDC = 'oidc',
SCIM = 'scim',
SSO_ENFORCEMENT = 'sso_enforcement',
XAA_AUTHENTICATION = 'xaa_authentication',
@@ -268,7 +269,7 @@ export enum Region {
DEV = 'DEV',
}
-export type SSOProvider = 'google-oauth2' | 'github' | 'gitlab' | 'saml'
+export type SSOProvider = 'google-oauth2' | 'github' | 'gitlab' | 'saml' | 'oidc'
export type LoginMethod = SSOProvider | 'password' | 'passkey' | null
export interface AuthBackends {
@@ -276,6 +277,7 @@ export interface AuthBackends {
gitlab?: boolean
github?: boolean
saml?: boolean
+ oidc?: boolean
}
export type ColumnChoice = string[] | 'DEFAULT'
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 721b91d59e95..eb69d3d0bb2c 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -149,6 +149,7 @@ def sso_login(request: HttpRequest, backend: str) -> HttpResponse:
sso_providers = get_instance_available_sso_providers()
# because SAML is configured at the domain-level, we have to assume it's enabled for someone in the instance
sso_providers["saml"] = settings.EE_AVAILABLE
+ sso_providers["oidc"] = settings.EE_AVAILABLE
is_reauth = is_sso_reauth_begin(request)
@@ -161,8 +162,8 @@ def sso_login(request: HttpRequest, backend: str) -> HttpResponse:
# The one known `connect_from` value is "posthog_code" - what PH Code uses when linking GH profile to PostHog user
connect_from = (request.GET.get("connect_from") or "").strip()
- if connect_from:
- # For linking a social provider, we keep the session and set the next URL to /account-connected/github-login
+ if connect_from and backend == "github":
+ # For linking GitHub, keep the session and set the next URL to /account-connected/github-login
# (see frontend AccountConnected). QueryDict must be copied before mutation (GET is often immutable).
query_dict = request.GET.copy()
query_dict["next"] = (
@@ -438,16 +439,18 @@ class LoginPrecheckSerializer(serializers.Serializer):
]
saml_available = IdentityProviderConfig.objects.get_is_saml_available_for_email(email)
+ oidc_available = IdentityProviderConfig.objects.get_is_oidc_available_for_email(email)
return {
"sso_enforcement": sso_enforcement_for_login_address(email, user),
"saml_available": saml_available,
+ "oidc_available": oidc_available,
"webauthn_credentials": webauthn_credentials,
- **self._available_local_methods(email, saml_available=saml_available),
+ **self._available_local_methods(email, saml_available=saml_available, oidc_available=oidc_available),
}
@staticmethod
- def _available_local_methods(email: str, *, saml_available: bool) -> dict[str, Any]:
+ def _available_local_methods(email: str, *, saml_available: bool, oidc_available: bool = False) -> dict[str, Any]:
"""
Report whether this account can log in with a password, and which of its linked social
identities are actually usable on this instance, so the login form can stop offering a
@@ -475,6 +478,8 @@ class LoginPrecheckSerializer(serializers.Serializer):
# SAML is domain-configured rather than instance-configured, so it isn't covered above.
usable_providers.add("saml")
linked_providers = set(user.social_auth.values_list("provider", flat=True))
+ if oidc_available:
+ usable_providers.add("oidc")
return {
"password_login_available": password_login_available,
@@ -1291,6 +1296,34 @@ def _sso_reauth_request(strategy: DjangoStrategy) -> HttpRequest | None:
return request
+def social_identity_matches_session(
+ strategy: DjangoStrategy,
+ backend: Any,
+ details: dict[str, Any] | None = None,
+ user: User | None = None,
+ social: Any = None,
+ **kwargs: Any,
+) -> None:
+ request = strategy.request
+ if not request or not request.user.is_authenticated or social is not None:
+ return
+
+ is_github_account_link = getattr(backend, "name", "") == "github" and (
+ strategy.session_get("next") or ""
+ ).startswith("/account-connected/github-login")
+ if is_github_account_link:
+ return
+
+ identity_email = ((details or {}).get("email") or "").lower()
+ if user is None or user.pk != request.user.pk or identity_email != request.user.email.lower():
+ logger.warning(
+ "SSO identity mismatch for authenticated session",
+ backend=getattr(backend, "name", ""),
+ session_user_id=request.user.pk,
+ )
+ raise AuthFailed(backend, "reauth_user_mismatch")
+
+
def social_reauth(
strategy: DjangoStrategy,
backend,
diff --git a/posthog/api/identity_provider_config.py b/posthog/api/identity_provider_config.py
index 18b6257e46e9..6d48974c86b9 100644
--- a/posthog/api/identity_provider_config.py
+++ b/posthog/api/identity_provider_config.py
@@ -1,4 +1,5 @@
from typing import Any, cast
+from urllib.parse import urlsplit
from django.db import transaction
from django.db.models import Q
@@ -19,7 +20,13 @@ from posthog.api.scoped_related_fields import OrgScopedPrimaryKeyRelatedField
from posthog.api.utils import action
from posthog.constants import AvailableFeature
from posthog.event_usage import groups
-from posthog.models.identity_provider_config import ConfigScope, DomainScope, IdentityProviderConfig, saml_configured_q
+from posthog.models.identity_provider_config import (
+ ConfigScope,
+ DomainScope,
+ IdentityProviderConfig,
+ oidc_configured_q,
+ saml_configured_q,
+)
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -67,6 +74,20 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",
)
has_saml = serializers.BooleanField(read_only=True, help_text="Whether SAML is fully configured on this config.")
+ has_oidc = serializers.BooleanField(
+ read_only=True, help_text="Whether OIDC has an issuer, client ID, and client secret."
+ )
+ has_oidc_client_secret = serializers.BooleanField(
+ read_only=True, help_text="Whether an encrypted OIDC client secret is saved."
+ )
+ oidc_client_secret = serializers.CharField(
+ required=False,
+ write_only=True,
+ allow_blank=True,
+ max_length=4096,
+ trim_whitespace=False,
+ help_text="OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.",
+ )
has_scim = serializers.BooleanField(
read_only=True, help_text="Whether SCIM is enabled and a bearer token is set on this config."
)
@@ -95,6 +116,11 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
"has_saml",
+ "has_oidc",
+ "has_oidc_client_secret",
+ "oidc_issuer_url",
+ "oidc_client_id",
+ "oidc_client_secret",
"saml_relay_state",
"saml_entity_id",
"saml_acs_url",
@@ -109,6 +135,10 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
"id_jag_allowed_clients",
)
extra_kwargs = {
+ "oidc_issuer_url": {
+ "help_text": "HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document."
+ },
+ "oidc_client_id": {"help_text": "Client ID of the organization's OIDC application."},
"name": {"help_text": "Display name for this IdP configuration (e.g. 'Okta production')."},
"domain_scope": {
"required": False,
@@ -182,12 +212,33 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
def validate_id_jag_issuer_url(self, value: str | None) -> str | None:
return self._validate_id_jag_url(value)
+ def validate_oidc_issuer_url(self, value: str) -> str:
+ normalized = value.strip()
+ if normalized:
+ parsed = urlsplit(normalized)
+ if parsed.scheme != "https" or parsed.query or parsed.fragment or parsed.username or parsed.password:
+ raise serializers.ValidationError(
+ "Use an HTTPS issuer URL without credentials, a query, or a fragment."
+ )
+ allowed, reason = is_url_allowed(normalized)
+ if not allowed:
+ raise serializers.ValidationError(f"URL is not allowed: {reason}")
+ return normalized
+
def validate_id_jag_jwks_url(self, value: str | None) -> str | None:
return self._validate_id_jag_url(value)
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
organization: Organization = self.context["view"].organization
+ if any(attrs.get(field) for field in ("oidc_issuer_url", "oidc_client_id", "oidc_client_secret")):
+ if not organization.is_feature_available(AvailableFeature.OIDC):
+ raise serializers.ValidationError(
+ {"oidc_issuer_url": "OIDC is not available for this organization."}, code="feature_not_available"
+ )
+ if attrs.get("config_scope", getattr(self.instance, "config_scope", None)) != ConfigScope.OIDC:
+ raise serializers.ValidationError({"config_scope": "Use an OIDC configuration for OIDC settings."})
+
if attrs.get("scim_enabled") is not None and not organization.is_feature_available(AvailableFeature.SCIM):
raise serializers.ValidationError(
{"scim_enabled": "SCIM provisioning is not available for this organization."},
@@ -203,11 +254,15 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
)
instance = cast(IdentityProviderConfig | None, self.instance)
- saml_values = {
- field: attrs.get(field, getattr(instance, field, None))
- for field in ("saml_entity_id", "saml_acs_url", "saml_x509_cert")
- }
- if not all(saml_values.values()):
+ is_oidc = attrs.get("config_scope", getattr(instance, "config_scope", None)) == ConfigScope.OIDC
+ config_fields = (
+ ("oidc_issuer_url", "oidc_client_id") if is_oidc else ("saml_entity_id", "saml_acs_url", "saml_x509_cert")
+ )
+ if not all(attrs.get(field, getattr(instance, field, None)) for field in config_fields):
+ return attrs
+ if is_oidc and not attrs.get(
+ "oidc_client_secret", ((instance.oidc_credentials or {}) if instance else {}).get("client_secret")
+ ):
return attrs
organization_domains = attrs.get("organization_domains")
@@ -221,19 +276,24 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
proposed_domain_ids = {domain.id for domain in organization_domains if domain.verified_at is not None}
domain_scope = attrs.get("domain_scope", getattr(instance, "domain_scope", None))
- other_saml_configs = IdentityProviderConfig.objects.filter(
- saml_configured_q(), organization=organization
- ).filter(Q(config_scope=ConfigScope.SAML) | Q(config_scope__isnull=True))
+ if is_oidc:
+ other_auth_configs = IdentityProviderConfig.objects.filter(
+ oidc_configured_q(), organization=organization, config_scope=ConfigScope.OIDC
+ )
+ else:
+ other_auth_configs = IdentityProviderConfig.objects.filter(
+ saml_configured_q(), organization=organization
+ ).filter(Q(config_scope=ConfigScope.SAML) | Q(config_scope__isnull=True))
if instance:
- other_saml_configs = other_saml_configs.exclude(pk=instance.pk)
+ other_auth_configs = other_auth_configs.exclude(pk=instance.pk)
if domain_scope == DomainScope.ALL:
- has_overlap = other_saml_configs.filter(
- Q(organization__domains__verified_at__isnull=False)
+ has_overlap = other_auth_configs.filter(
+ Q(domain_scope=DomainScope.ALL, organization__domains__verified_at__isnull=False)
| Q(linked_identity_provider_configs__organization_domain__verified_at__isnull=False)
).exists()
elif proposed_domain_ids:
- has_overlap = other_saml_configs.filter(
+ has_overlap = other_auth_configs.filter(
Q(
domain_scope=DomainScope.ALL,
organization__domains__id__in=proposed_domain_ids,
@@ -248,9 +308,10 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
has_overlap = False
if has_overlap:
+ protocol = "OIDC" if is_oidc else "SAML"
raise serializers.ValidationError(
{
- "domain_scope": "This SAML configuration overlaps with another SAML configuration on one or more verified domains. Choose different domains before saving."
+ "domain_scope": f"This {protocol} configuration overlaps with another {protocol} configuration on one or more verified domains. Choose different domains before saving."
}
)
@@ -271,9 +332,17 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
]
)
+ @staticmethod
+ def _merge_oidc_client_secret(validated_data: dict[str, Any]) -> None:
+ if "oidc_client_secret" not in validated_data:
+ return
+ client_secret = validated_data.pop("oidc_client_secret")
+ validated_data["oidc_credentials"] = {"client_secret": client_secret} if client_secret else {}
+
@transaction.atomic
def create(self, validated_data: dict[str, Any]) -> IdentityProviderConfig:
validated_data["organization"] = self.context["view"].organization
+ self._merge_oidc_client_secret(validated_data)
scim_enabled = validated_data.pop("scim_enabled", None)
organization_domains = validated_data.pop("organization_domains", [])
validated_data.pop("scim_bearer_token", None)
@@ -288,6 +357,7 @@ class IdentityProviderConfigSerializer(serializers.ModelSerializer):
@transaction.atomic
def update(self, instance: IdentityProviderConfig, validated_data: dict[str, Any]) -> IdentityProviderConfig:
+ self._merge_oidc_client_secret(validated_data)
scim_enabled = validated_data.pop("scim_enabled", None)
organization_domains = validated_data.pop("organization_domains", None)
validated_data.pop("scim_bearer_token", None)
diff --git a/posthog/api/oidc.py b/posthog/api/oidc.py
new file mode 100644
index 000000000000..5179c78a7b93
--- /dev/null
+++ b/posthog/api/oidc.py
@@ -0,0 +1,258 @@
+import time
+from functools import cached_property
+from typing import Any, cast
+from urllib.parse import urlsplit
+
+from django.core.exceptions import ValidationError
+
+import jwt
+import structlog
+from prometheus_client import Counter, Histogram
+from requests import HTTPError, RequestException, Response, Timeout
+from social_core.backends.open_id_connect import OpenIdConnectAuth
+from social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameter, AuthTokenError
+from urllib3.util import Timeout as Urllib3Timeout
+
+from posthog.constants import AvailableFeature
+from posthog.dataclasses import frozen
+from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.security.pinned_requests import SSRFBlockedError, pinned_session
+
+BasicAuthCredentials = tuple[str, str]
+
+logger = structlog.get_logger("posthog.auth.oidc")
+OIDC_REQUEST_FAILURES = Counter(
+ "posthog_oidc_request_failures_total",
+ "OIDC requests that failed before authentication could continue.",
+ labelnames=["phase", "failure_category"],
+)
+OIDC_REQUEST_DURATION = Histogram(
+ "posthog_oidc_request_duration_seconds",
+ "OIDC request duration.",
+ labelnames=["phase"],
+)
+
+
+OIDC_FETCH_TIMEOUT_SECONDS = 10
+
+
+@frozen
+class OIDCClientCredentials:
+ client_id: str
+ client_secret: str
+
+ def as_tuple(self) -> BasicAuthCredentials:
+ return self.client_id, self.client_secret
+
+
+class MultitenantOIDCAuth(OpenIdConnectAuth):
+ DEFAULT_USE_PKCE = True
+ JWT_DECODE_OPTIONS = {"require": ["iss", "sub", "aud", "exp", "iat", "nonce"]}
+
+ @cached_property
+ def identity_provider_config(self) -> IdentityProviderConfig:
+ config_id = self.strategy.session_get("oidc_config_id")
+ email = self.strategy.session_get("oidc_email")
+ organization_id = self.strategy.session_get("oidc_organization_id")
+ if not isinstance(email, str) or organization_id is None:
+ raise AuthFailed(self, "OIDC email is not available.")
+ try:
+ config = (
+ IdentityProviderConfig.objects.get_queryset()
+ .oidc_for_email(email)
+ .select_related("organization")
+ .get(id=config_id, organization_id=organization_id)
+ )
+ except (IdentityProviderConfig.DoesNotExist, ValidationError, ValueError):
+ raise AuthFailed(self, "OIDC configuration is not available.")
+ if not config.has_oidc or not config.organization.is_feature_available(AvailableFeature.OIDC):
+ raise AuthFailed(self, "OIDC is not available for this organization.")
+ return config
+
+ def auth_url(self) -> str:
+ email = self.data.get("email")
+ if not email or not isinstance(email, str):
+ raise AuthMissingParameter(self, "email")
+ configs = [
+ config
+ for config in IdentityProviderConfig.objects.get_queryset()
+ .oidc_for_email(email)
+ .select_related("organization")
+ if config.has_oidc and config.organization.is_feature_available(AvailableFeature.OIDC)
+ ]
+ if len(configs) != 1:
+ raise AuthFailed(self, "OIDC requires one configured identity provider for this email domain.")
+ self.strategy.session_set("oidc_config_id", str(configs[0].id))
+ self.strategy.session_set("oidc_email", email)
+ self.strategy.session_set("oidc_organization_id", str(configs[0].organization_id))
+ return super().auth_url()
+
+ def oidc_endpoint(self) -> str:
+ return self.identity_provider_config.oidc_issuer_url.rstrip("/")
+
+ def oidc_config(self) -> dict[str, Any]:
+ return self.discovery_document
+
+ def get_json(self, url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ try:
+ document = super().get_json(url, *args, **kwargs)
+ except (TypeError, ValueError) as error:
+ raise AuthFailed(self, "The OIDC provider returned invalid JSON.") from error
+ if not isinstance(document, dict):
+ raise AuthFailed(self, "The OIDC provider returned an invalid JSON document.")
+ return document
+
+ @cached_property
+ def discovery_document(self) -> dict[str, Any]:
+ document = self.get_json(f"{self.oidc_endpoint()}/.well-known/openid-configuration")
+ issuer = document.get("issuer")
+ configured_issuer = self.identity_provider_config.oidc_issuer_url
+ if not isinstance(issuer, str) or issuer.rstrip("/") != configured_issuer.rstrip("/"):
+ raise AuthFailed(self, "The OIDC discovery issuer does not match the configured issuer.")
+ for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
+ endpoint = document.get(field)
+ if not isinstance(endpoint, str) or urlsplit(endpoint).scheme != "https":
+ raise AuthFailed(self, "OIDC discovery requires HTTPS endpoints.")
+ return document
+
+ def _get_client_credentials(self) -> OIDCClientCredentials:
+ config = self.identity_provider_config
+ return OIDCClientCredentials(
+ client_id=config.oidc_client_id,
+ client_secret=config.oidc_credentials["client_secret"],
+ )
+
+ def get_key_and_secret(self) -> BasicAuthCredentials:
+ return self._get_client_credentials().as_tuple()
+
+ def get_jwks_keys(self) -> list[dict[str, Any]]:
+ return self.get_remote_jwks_keys()
+
+ def get_remote_jwks_keys(self) -> list[dict[str, Any]]:
+ try:
+ document = self.request(self.jwks_uri()).json()
+ except (TypeError, ValueError) as error:
+ raise AuthFailed(self, "The OIDC provider returned invalid JWKS JSON.") from error
+ if not isinstance(document, dict) or not isinstance(document.get("keys"), list):
+ raise AuthFailed(self, "The OIDC provider returned an invalid JWKS document.")
+ if not all(isinstance(key, dict) for key in document["keys"]):
+ raise AuthFailed(self, "The OIDC provider returned invalid JWKS keys.")
+ return cast(list[dict[str, Any]], document["keys"])
+
+ def find_valid_key(self, id_token: str) -> dict[str, Any] | None:
+ try:
+ key_id = jwt.get_unverified_header(id_token).get("kid")
+ keys = [
+ {**key, "alg": "RS256"}
+ for key in self.get_jwks_keys()
+ if key.get("kty") == "RSA"
+ and key.get("alg", "RS256") == "RS256"
+ and key.get("use", "sig") == "sig"
+ and (key_id is None or key.get("kid") == key_id)
+ ]
+ return keys[0] if len(keys) == 1 else None
+ except (AttributeError, KeyError, TypeError, ValueError, jwt.InvalidTokenError) as error:
+ raise AuthTokenError(self, "The OIDC ID token or JWKS is invalid.") from error
+
+ def validate_claims(self, id_token: dict[str, Any]) -> None:
+ client_id = self.identity_provider_config.oidc_client_id
+ authorized_party = id_token.get("azp")
+ audiences = id_token.get("aud")
+ if (authorized_party is not None and authorized_party != client_id) or (
+ isinstance(audiences, list) and len(audiences) > 1 and authorized_party != client_id
+ ):
+ raise AuthTokenError(self, "The OIDC authorized party does not match the client ID.")
+ super().validate_claims(id_token)
+
+ def _request_phase(self, url: str) -> str:
+ if url.endswith("/.well-known/openid-configuration"):
+ return "discovery"
+ if not hasattr(self, "strategy"):
+ return "unknown"
+ if url == self.access_token_url():
+ return "token"
+ if url == self.jwks_uri():
+ return "jwks"
+ if url == self.userinfo_url():
+ return "userinfo"
+ return "unknown"
+
+ def _request_failure_category(self, error: RequestException | SSRFBlockedError) -> str:
+ if isinstance(error, SSRFBlockedError):
+ return "ssrf_blocked"
+ if isinstance(error, Timeout):
+ return "timeout"
+ if isinstance(error, HTTPError):
+ return "http_error"
+ return "request_error"
+
+ def request(self, url: str, method: str = "GET", *args: Any, **kwargs: Any) -> Response:
+ if urlsplit(url).scheme != "https":
+ raise AuthFailed(self, "OIDC requires HTTPS endpoints.")
+ phase = self._request_phase(url)
+ started_at = time.monotonic()
+ kwargs["timeout"] = Urllib3Timeout(
+ total=OIDC_FETCH_TIMEOUT_SECONDS,
+ connect=OIDC_FETCH_TIMEOUT_SECONDS,
+ read=OIDC_FETCH_TIMEOUT_SECONDS,
+ )
+ kwargs["allow_redirects"] = False
+ kwargs["stream"] = False
+ try:
+ with pinned_session(url) as session:
+ response = session.request(method, url, *args, **kwargs)
+ try:
+ if response.is_redirect:
+ raise AuthFailed(self, "OIDC endpoint redirects are not supported.")
+ response.raise_for_status()
+
+ return response
+ finally:
+ response.close()
+ except (RequestException, SSRFBlockedError) as error:
+ failure_category = self._request_failure_category(error)
+ config = self.identity_provider_config
+ duration_seconds = time.monotonic() - started_at
+ OIDC_REQUEST_FAILURES.labels(phase, failure_category).inc()
+ logger.warning(
+ "oidc_request_failed",
+ phase=phase,
+ failure_category=failure_category,
+ identity_provider_config_id=str(config.id),
+ organization_id=str(config.organization_id),
+ duration_seconds=duration_seconds,
+ )
+ raise AuthConnectionError(self) from error
+ finally:
+ OIDC_REQUEST_DURATION.labels(phase).observe(time.monotonic() - started_at)
+
+ def user_data(self, access_token: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ id_token = cast(dict[str, Any] | None, self.id_token)
+ if id_token is None:
+ raise AuthFailed(self, "OIDC did not return a valid ID token.")
+ userinfo = super().user_data(access_token, *args, **kwargs)
+ if not isinstance(userinfo, dict) or userinfo.get("sub") != id_token.get("sub"):
+ raise AuthFailed(self, "The OIDC user does not match the ID token.")
+ email = userinfo.get("email")
+ if userinfo.get("email_verified") is not True or not isinstance(email, str):
+ raise AuthFailed(self, "OIDC requires a verified email address from the identity provider.")
+ if not (
+ IdentityProviderConfig.objects.get_queryset()
+ .oidc_for_email(email)
+ .filter(id=self.identity_provider_config.id)
+ .exists()
+ ):
+ raise AuthFailed(self, "The OIDC email domain does not belong to this identity provider configuration.")
+ return userinfo
+
+ def get_user_id(self, details: dict[str, Any], response: dict[str, Any]) -> str:
+ issuer = self.identity_provider_config.oidc_issuer_url.rstrip("/")
+ user_id = f"{issuer}:{response['sub']}"
+ if len(user_id) > 255:
+ raise AuthFailed(self, "The OIDC user identifier is too long.")
+ return user_id
+
+ def extra_data(
+ self, user: Any, uid: str, response: dict[str, Any], details: dict[str, Any], *args: Any, **kwargs: Any
+ ) -> dict:
+ return {}
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index bbd5396557c2..3cc123ed2142 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -95,6 +95,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -118,6 +119,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": True,
"social_providers": [],
@@ -253,6 +255,7 @@ class TestLoginPrecheckAPI(APIBaseTest):
{
"sso_enforcement": None,
"saml_available": False,
+ "oidc_available": False,
"webauthn_credentials": [],
"password_login_available": False,
"social_providers": [],
diff --git a/posthog/api/test/test_identity_provider_config.py b/posthog/api/test/test_identity_provider_config.py
index 92baef311f40..16a375255565 100644
--- a/posthog/api/test/test_identity_provider_config.py
+++ b/posthog/api/test/test_identity_provider_config.py
@@ -1,4 +1,5 @@
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.conf import settings
from django.utils import timezone
@@ -19,6 +20,162 @@ from ee.models.scim_request_log import SCIMRequestLog
class TestIdentityProviderConfigAPI(APIBaseTest):
+ @patch("posthog.api.identity_provider_config.is_url_allowed", return_value=(True, ""))
+ def test_oidc_configuration_keeps_client_secret_private(self, _mock_url_allowed):
+ self._make_admin()
+ self._enable_features(AvailableFeature.OIDC)
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {
+ "config_scope": "oidc",
+ "domain_scope": "all",
+ "oidc_issuer_url": "https://idp.example.com",
+ "oidc_client_id": "example-client",
+ "oidc_client_secret": "example-secret",
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertTrue(response.json()["has_oidc"])
+ self.assertTrue(response.json()["has_oidc_client_secret"])
+ self.assertNotIn("oidc_client_secret", response.json())
+ self.assertNotIn("oidc_credentials", response.json())
+ config = IdentityProviderConfig.objects.get(id=response.json()["id"])
+ self.assertEqual(config.oidc_credentials, {"client_secret": "example-secret"})
+ from django.db import connection
+
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT oidc_credentials FROM posthog_identityproviderconfig WHERE id = %s", [config.id])
+ self.assertNotIn("example-secret", str(cursor.fetchone()[0]))
+
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/", {"name": "Renamed provider"}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ config.refresh_from_db()
+ self.assertEqual(config.oidc_credentials, {"client_secret": "example-secret"})
+
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/", {"oidc_client_secret": "new-secret"}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ config.refresh_from_db()
+ self.assertEqual(config.oidc_credentials, {"client_secret": "new-secret"})
+
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/", {"oidc_client_secret": ""}
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertFalse(response.json()["has_oidc"])
+
+ def test_oidc_configuration_requires_its_own_entitlement(self):
+ self._make_admin()
+ self._enable_features(AvailableFeature.SAML)
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {"config_scope": "oidc", "oidc_client_id": "example-client"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["code"], "feature_not_available")
+
+ def test_oidc_configuration_rejects_overlapping_verified_domains(self):
+ self._make_admin()
+ self._enable_features(AvailableFeature.OIDC)
+ OrganizationDomain.objects.create(
+ organization=self.organization, domain="example.com", verified_at=timezone.now()
+ )
+ IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="oidc",
+ domain_scope="all",
+ oidc_issuer_url="https://idp.example.com",
+ oidc_client_id="example-client",
+ oidc_credentials={"client_secret": "example-secret"},
+ )
+ config = IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="oidc",
+ domain_scope="all",
+ oidc_issuer_url="https://other.example.com",
+ oidc_client_id="other-client",
+ )
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",
+ {"oidc_client_secret": "other-secret"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("overlaps", response.json()["detail"])
+
+ @patch("posthog.api.identity_provider_config.is_url_allowed", return_value=(True, ""))
+ def test_oidc_all_domain_configuration_does_not_overlap_unlinked_selected_configuration(self, _mock_url_allowed):
+ self._make_admin()
+ self._enable_features(AvailableFeature.OIDC)
+ OrganizationDomain.objects.create(
+ organization=self.organization, domain="example.com", verified_at=timezone.now()
+ )
+ IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="oidc",
+ domain_scope="selected",
+ oidc_issuer_url="https://idp.example.com",
+ oidc_client_id="example-client",
+ oidc_credentials={"client_secret": "example-secret"},
+ )
+
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {
+ "config_scope": "oidc",
+ "domain_scope": "all",
+ "oidc_issuer_url": "https://other.example.com",
+ "oidc_client_id": "other-client",
+ "oidc_client_secret": "other-secret",
+ },
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ @patch("posthog.api.identity_provider_config.is_url_allowed", return_value=(True, ""))
+ def test_cleared_oidc_secret_is_not_treated_as_configured_for_overlap(self, _mock_url_allowed):
+ self._make_admin()
+ self._enable_features(AvailableFeature.OIDC)
+ OrganizationDomain.objects.create(
+ organization=self.organization, domain="example.com", verified_at=timezone.now()
+ )
+ config = IdentityProviderConfig.objects.create(
+ organization=self.organization,
+ config_scope="oidc",
+ domain_scope="all",
+ oidc_issuer_url="https://idp.example.com",
+ oidc_client_id="example-client",
+ oidc_credentials={"client_secret": "example-secret"},
+ )
+ response = self.client.patch(
+ f"/api/organizations/@current/identity_provider_configs/{config.id}/",
+ {"oidc_client_secret": ""},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {
+ "config_scope": "oidc",
+ "domain_scope": "all",
+ "oidc_issuer_url": "https://other.example.com",
+ "oidc_client_id": "other-client",
+ "oidc_client_secret": "other-secret",
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ def test_oidc_configuration_rejects_insecure_issuer(self):
+ self._make_admin()
+ self._enable_features(AvailableFeature.OIDC)
+ response = self.client.post(
+ "/api/organizations/@current/identity_provider_configs/",
+ {"config_scope": "oidc", "oidc_issuer_url": "http://idp.example.com"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def _make_admin(self) -> None:
self.organization_membership.level = OrganizationMembership.Level.ADMIN
self.organization_membership.save()
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index c3cb40382606..aa2099c10c06 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -2854,9 +2854,18 @@ class TestInviteSignupAPI(APIBaseTest):
{"key": AvailableFeature.SAML, "name": AvailableFeature.SAML},
]
organization.save()
- OrganizationDomain.objects.create(
+ domain = OrganizationDomain.objects.create(
domain="posthog_sss_test.com", organization=organization, sso_enforcement="saml", verified_at=timezone.now()
)
+ config = IdentityProviderConfig.objects.create(
+ organization=organization,
+ config_scope="saml",
+ domain_scope="all",
+ saml_entity_id="https://idp.example.com",
+ saml_acs_url="https://idp.example.com/saml",
+ saml_x509_cert="test-certificate",
+ )
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
invite: OrganizationInvite = OrganizationInvite.objects.create(
target_email="test+sso@posthog_sss_test.com", organization=organization
diff --git a/posthog/api/test/test_webauthn.py b/posthog/api/test/test_webauthn.py
index c285f62b8f8d..0ba8d0b86141 100644
--- a/posthog/api/test/test_webauthn.py
+++ b/posthog/api/test/test_webauthn.py
@@ -12,12 +12,39 @@ from parameterized import parameterized
from rest_framework import status
from posthog.api.webauthn import WEBAUTHN_REGISTRATION_CHALLENGE_KEY, WebAuthnLoginViewSet
-from posthog.models import User
+from posthog.models import Organization, User
+from posthog.models.identity_provider_config import IdentityProviderConfig
+from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.session.models import Session
+def _enforce_sso(user: User, organization: Organization) -> None:
+ email_domain = user.email.split("@", 1)[1]
+ organization.available_product_features = [
+ {"key": "sso_enforcement", "name": "sso_enforcement"},
+ {"key": "saml", "name": "saml"},
+ ]
+ organization.save()
+
+ domain = OrganizationDomain.objects.create(
+ domain=email_domain,
+ organization=organization,
+ verified_at=timezone.now(),
+ sso_enforcement="saml",
+ )
+ config = IdentityProviderConfig.objects.create(
+ organization=organization,
+ config_scope="saml",
+ domain_scope="all",
+ saml_entity_id="https://idp.example.com",
+ saml_acs_url="https://idp.example.com/saml",
+ saml_x509_cert="test-certificate",
+ )
+ LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
+
+
class TestWebAuthnRegistration(APIBaseTest):
"""Tests for WebAuthn passkey registration flow."""
@@ -61,40 +88,14 @@ class TestWebAuthnRegistration(APIBaseTest):
self.assertEqual(len(data["excludeCredentials"]), 1)
def test_registration_begin_disallowed_when_sso_enforced(self):
- email_domain = self.user.email.split("@", 1)[1]
-
- self.organization.available_product_features = [
- {"key": "sso_enforcement", "name": "sso_enforcement"},
- {"key": "saml", "name": "saml"},
- ]
- self.organization.save()
-
- OrganizationDomain.objects.create(
- domain=email_domain,
- organization=self.organization,
- verified_at=timezone.now(),
- sso_enforcement="saml",
- )
+ _enforce_sso(self.user, self.organization)
response = self.client.post("/api/webauthn/register/begin/")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("requires SSO", response.json().get("detail", ""))
def test_registration_complete_disallowed_when_sso_enforced(self):
- email_domain = self.user.email.split("@", 1)[1]
-
- self.organization.available_product_features = [
- {"key": "sso_enforcement", "name": "sso_enforcement"},
- {"key": "saml", "name": "saml"},
- ]
- self.organization.save()
-
- OrganizationDomain.objects.create(
- domain=email_domain,
- organization=self.organization,
- verified_at=timezone.now(),
- sso_enforcement="saml",
- )
+ _enforce_sso(self.user, self.organization)
session = self.client.session
session[WEBAUTHN_REGISTRATION_CHALLENGE_KEY] = "dummy"
@@ -405,20 +406,7 @@ class TestWebAuthnLogin(APIBaseTest):
from posthog.api.webauthn import user_uuid_to_handle
- email_domain = self.user.email.split("@", 1)[1]
-
- self.organization.available_product_features = [
- {"key": "sso_enforcement", "name": "sso_enforcement"},
- {"key": "saml", "name": "saml"},
- ]
- self.organization.save()
-
- OrganizationDomain.objects.create(
- domain=email_domain,
- organization=self.organization,
- verified_at=timezone.now(),
- sso_enforcement="saml",
- )
+ _enforce_sso(self.user, self.organization)
self.client.post("/api/webauthn/login/begin/")
mock_verify.return_value = MagicMock(new_sign_count=1)
diff --git a/posthog/constants.py b/posthog/constants.py
index bf8f9af6b279..463aea2865cc 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -15,6 +15,7 @@ class AvailableFeature(StrEnum):
ORGANIZATIONS_PROJECTS = "organizations_projects"
SOCIAL_SSO = "social_sso"
SAML = "saml"
+ OIDC = "oidc"
SCIM = "scim"
SSO_ENFORCEMENT = "sso_enforcement"
ADVANCED_PERMISSIONS = "advanced_permissions" # TODO: Remove this once access_control is propagated
@@ -402,6 +403,11 @@ LOGIN_METHODS = [
"display": "SAML",
"backends": ["saml", "ee.api.authentication.MultitenantSAMLAuth"],
},
+ {
+ "key": "oidc",
+ "display": "OIDC",
+ "backends": ["oidc", "posthog.api.oidc.MultitenantOIDCAuth"],
+ },
{
"key": "passkey",
"display": "Passkey",
diff --git a/posthog/migrations/1362_identity_provider_oidc.py b/posthog/migrations/1362_identity_provider_oidc.py
new file mode 100644
index 000000000000..fa48eda62cee
--- /dev/null
+++ b/posthog/migrations/1362_identity_provider_oidc.py
@@ -0,0 +1,39 @@
+# Generated by Django 5.2.17 on 2026-09-09 11:35
+
+from django.db import migrations, models
+
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1361_asyncdeletion_event_deletion_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="identityproviderconfig",
+ name="oidc_client_id",
+ field=models.CharField(blank=True, db_default="", default="", max_length=512),
+ ),
+ migrations.AddField(
+ model_name="identityproviderconfig",
+ name="oidc_credentials",
+ field=posthog.helpers.encrypted_fields.EncryptedJSONField(blank=True, default=dict, null=True),
+ ),
+ migrations.AddField(
+ model_name="identityproviderconfig",
+ name="oidc_issuer_url",
+ field=models.URLField(blank=True, db_default="", default="", max_length=512),
+ ),
+ migrations.AlterField(
+ model_name="identityproviderconfig",
+ name="config_scope",
+ field=models.CharField(
+ blank=True,
+ choices=[("saml", "Saml"), ("oidc", "Oidc"), ("scim", "Scim"), ("xaa", "Xaa")],
+ max_length=4,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 71e6596b2989..0baf18c70334 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1361_asyncdeletion_event_deletion_type
+1362_identity_provider_oidc
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 65a784e29d2a..5456b01279a7 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -319,6 +319,7 @@ field_with_masked_contents: dict[AuditableScope, list[str]] = {
],
"IdentityProviderConfig": [
"scim_bearer_token",
+ "oidc_credentials",
"saml_x509_cert",
],
"User": [
diff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.py
index ff1946cd3242..177ca37d5aae 100644
--- a/posthog/models/identity_provider_config.py
+++ b/posthog/models/identity_provider_config.py
@@ -8,6 +8,7 @@ import structlog
from posthog.constants import AvailableFeature
from posthog.dataclasses import frozen
+from posthog.helpers.encrypted_fields import EncryptedJSONField
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import UUIDModel
@@ -40,6 +41,7 @@ def has_verified_organization_domain_q() -> models.Q:
class ConfigScope(models.TextChoices):
SAML = "saml"
+ OIDC = "oidc"
SCIM = "scim"
ID_JAG = (
"xaa",
@@ -58,6 +60,17 @@ def saml_configured_q() -> models.Q:
)
+def oidc_configured_q() -> models.Q:
+ # `oidc_credentials` encrypts each value but not the keys, so only a key's presence is
+ # queryable. An empty secret is stored as an empty mapping, never an empty-string value.
+ return ~models.Q(
+ models.Q(oidc_issuer_url="")
+ | models.Q(oidc_issuer_url__isnull=True)
+ | models.Q(oidc_client_id="")
+ | models.Q(oidc_client_id__isnull=True)
+ ) & models.Q(oidc_credentials__has_key="client_secret")
+
+
class IdentityProviderConfigQuerySet(models.QuerySet["IdentityProviderConfig"]):
def for_scope(self, config_scope: str) -> "IdentityProviderConfigQuerySet":
return self.filter(models.Q(config_scope=config_scope) | models.Q(config_scope__isnull=True))
@@ -81,6 +94,9 @@ class IdentityProviderConfigQuerySet(models.QuerySet["IdentityProviderConfig"]):
def saml_for_email(self, email: str) -> "IdentityProviderConfigQuerySet":
return self.for_scope(ConfigScope.SAML).filter(saml_configured_q()).with_verified_domain_for_email(email)
+ def oidc_for_email(self, email: str) -> "IdentityProviderConfigQuerySet":
+ return self.filter(config_scope=ConfigScope.OIDC).with_verified_domain_for_email(email)
+
class IdentityProviderConfigManager(models.Manager["IdentityProviderConfig"]):
def get_queryset(self) -> IdentityProviderConfigQuerySet:
@@ -137,6 +153,12 @@ class IdentityProviderConfigManager(models.Manager["IdentityProviderConfig"]):
configs = self.get_queryset().saml_for_email(email).select_related("organization")
return any(config.organization.is_feature_available(AvailableFeature.SAML) for config in configs)
+ def get_is_oidc_available_for_email(self, email: str) -> bool:
+ configs = self.get_queryset().oidc_for_email(email).select_related("organization")
+ return any(
+ config.has_oidc and config.organization.is_feature_available(AvailableFeature.OIDC) for config in configs
+ )
+
class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
"""
@@ -173,6 +195,10 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
saml_entity_id = models.CharField(max_length=512, blank=True, null=True)
saml_acs_url = models.CharField(max_length=512, blank=True, null=True)
saml_x509_cert = models.TextField(blank=True, null=True)
+ oidc_issuer_url = models.URLField(max_length=512, blank=True, default="", db_default="")
+ oidc_client_id = models.CharField(max_length=512, blank=True, default="", db_default="")
+ # oidc supports multiple forms of authentication. JSON field for forward compatibility.
+ oidc_credentials = EncryptedJSONField(default=dict, blank=True, null=True)
# Round-trips through the IdP as RelayState to route an assertion back to this config, and is
# also the prefix of every `UserSocialAuth.uid` issued through it. Changing the value on a
# config already in use orphans those identities, so it is assigned once and never edited.
@@ -243,6 +269,17 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
return domains
return domains.filter(linked_identity_provider_configs__identity_provider_config=self)
+ @property
+ def has_oidc_client_secret(self) -> bool:
+ return bool((self.oidc_credentials or {}).get("client_secret"))
+
+ @property
+ def has_oidc(self) -> bool:
+ """
+ Returns whether OIDC is configured. Does not validate the organization has the required license.
+ """
+ return bool(self.oidc_issuer_url) and bool(self.oidc_client_id) and self.has_oidc_client_secret
+
@property
def has_saml(self) -> bool:
"""
diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.py
index f0169eaaba0b..6bef1607d027 100644
--- a/posthog/models/organization_domain.py
+++ b/posthog/models/organization_domain.py
@@ -66,7 +66,7 @@ class OrganizationDomainManager(models.Manager):
candidate_sso_enforcement = query["sso_enforcement"]
- available_product_features = query["organization__available_product_features"]
+ available_product_features = query["organization__available_product_features"] or []
available_product_feature_keys = [feature["key"] for feature in available_product_features]
# Check organization has a license to enforce SSO
if AvailableFeature.SSO_ENFORCEMENT not in available_product_feature_keys:
@@ -87,6 +87,13 @@ class OrganizationDomainManager(models.Manager):
organization=str(query["organization_id"]),
)
return None
+ if not IdentityProviderConfig.objects.get_is_saml_available_for_email(email):
+ return None
+ elif candidate_sso_enforcement == "oidc":
+ if AvailableFeature.OIDC not in available_product_feature_keys:
+ return None
+ if not IdentityProviderConfig.objects.get_is_oidc_available_for_email(email):
+ return None
else:
sso_providers = get_instance_available_sso_providers()
if not sso_providers[candidate_sso_enforcement]:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4d6a359520f2..2c45a7235fe8 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -298,7 +298,8 @@ SOCIAL_AUTH_PIPELINE = (
"social_core.pipeline.social_auth.auth_allowed",
"ee.api.authentication.social_auth_allowed",
"social_core.pipeline.social_auth.social_user",
- # Must stay ahead of association/provisioning so a mismatched re-auth identity is rejected first
+ # Must stay ahead of association/provisioning so a mismatched authenticated identity is rejected first
+ "posthog.api.authentication.social_identity_matches_session",
"posthog.api.authentication.social_reauth",
"social_core.pipeline.social_auth.associate_by_email",
"posthog.api.signup.social_create_user",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9486d159e30b..f24aeaf104fc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19662,6 +19662,7 @@ export namespace Schemas {
/**
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa
*/
@@ -19670,6 +19671,7 @@ export namespace Schemas {
export const ConfigScopeEnum = {
Saml: 'saml',
+ Oidc: 'oidc',
Scim: 'scim',
Xaa: 'xaa',
} as const;
@@ -48622,6 +48624,7 @@ export namespace Schemas {
/** Feature configured by this identity provider configuration.
*
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa */
config_scope?: ConfigScopeEnum | BlankEnum | null;
@@ -48631,6 +48634,22 @@ export namespace Schemas {
readonly updated_at: string;
/** Whether SAML is fully configured on this config. */
readonly has_saml: boolean;
+ /** Whether OIDC has an issuer, client ID, and client secret. */
+ readonly has_oidc: boolean;
+ /** Whether an encrypted OIDC client secret is saved. */
+ readonly has_oidc_client_secret: boolean;
+ /** HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document. */
+ oidc_issuer_url?: string;
+ /**
+ * Client ID of the organization's OIDC application.
+ * @maxLength 512
+ */
+ oidc_client_id?: string;
+ /**
+ * OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.
+ * @maxLength 4096
+ */
+ oidc_client_secret?: string;
/** Stable UUID sent as SAML RelayState to route authentication responses to this IdP configuration. */
readonly saml_relay_state: string;
/**
@@ -67573,6 +67592,7 @@ export namespace Schemas {
/** Feature configured by this identity provider configuration.
*
* * `saml` - Saml
+ * * `oidc` - Oidc
* * `scim` - Scim
* * `xaa` - Xaa */
config_scope?: ConfigScopeEnum | BlankEnum | null;
@@ -67582,6 +67602,22 @@ export namespace Schemas {
readonly updated_at?: string;
/** Whether SAML is fully configured on this config. */
readonly has_saml?: boolean;
+ /** Whether OIDC has an issuer, client ID, and client secret. */
+ readonly has_oidc?: boolean;
+ /** Whether an encrypted OIDC client secret is saved. */
+ readonly has_oidc_client_secret?: boolean;
+ /** HTTPS issuer URL. Must exactly match the issuer in the OIDC discovery document. */
+ oidc_issuer_url?: string;
+ /**
+ * Client ID of the organization's OIDC application.
+ * @maxLength 512
+ */
+ oidc_client_id?: string;
+ /**
+ * OIDC client secret. Omit to keep the saved secret. Set to an empty string to remove it. Never returned in responses.
+ * @maxLength 4096
+ */
+ oidc_client_secret?: string;
/** Stable UUID sent as SAML RelayState to route authentication responses to this IdP configuration. */
readonly saml_relay_state?: string;
/**