authentik.sources.oauth.types.oidc

OpenID Connect OAuth Views

  1"""OpenID Connect OAuth Views"""
  2
  3from typing import Any
  4
  5from jwt import PyJWTError, decode, get_unverified_header
  6from requests.auth import AuthBase, HTTPBasicAuth
  7
  8from authentik.lib.jwt_mldsa import key_from_jwk
  9from authentik.sources.oauth.clients.oauth2 import UserprofileHeaderAuthClient
 10from authentik.sources.oauth.models import AuthorizationCodeAuthMethod, OAuthSource
 11from authentik.sources.oauth.types.registry import SourceType, registry
 12from authentik.sources.oauth.views.callback import OAuthCallback
 13from authentik.sources.oauth.views.redirect import OAuthRedirect
 14
 15
 16class OpenIDConnectOAuthRedirect(OAuthRedirect):
 17    """OpenIDConnect OAuth2 Redirect"""
 18
 19    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
 20        return {
 21            "scope": ["openid", "email", "profile"],
 22        }
 23
 24
 25class OpenIDConnectClient(UserprofileHeaderAuthClient):
 26    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
 27        args = super().get_access_token_args(callback, code)
 28        client_id = self.get_client_id()
 29        client_secret = self.get_client_secret()
 30        if self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.POST_BODY:
 31            args["client_id"] = client_id
 32            if client_secret:
 33                args["client_secret"] = client_secret
 34        elif client_secret:
 35            # Basic auth, credentials are sent in the header
 36            args.pop("client_id", None)
 37            args.pop("client_secret", None)
 38        return args
 39
 40    def get_access_token_auth(self) -> AuthBase | None:
 41        client_secret = self.get_client_secret()
 42        if (
 43            self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.BASIC_AUTH
 44            and client_secret
 45        ):
 46            return HTTPBasicAuth(self.get_client_id(), client_secret)
 47        return None
 48
 49    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
 50        profile = super().get_profile_info(token)
 51        if profile:
 52            return profile
 53        if "id_token" not in token:
 54            self.logger.warning("no id_token given")
 55            return None
 56        id_token = token["id_token"]
 57        try:
 58            raw = get_unverified_header(id_token)
 59            jwk = [
 60                key for key in self.source.oidc_jwks.get("keys", []) if key.get("kid") == raw["kid"]
 61            ][0]
 62            key, _ = key_from_jwk(jwk)
 63            return decode(
 64                id_token,
 65                key=key,
 66                algorithms=[raw["alg"]],
 67                audience=self.get_client_id(),
 68                options={"verify_iss": False},
 69            )
 70        except (PyJWTError, IndexError, ValueError) as exc:
 71            self.logger.warning("Failed to decode id_token", exc=exc)
 72            return None
 73
 74
 75class OpenIDConnectOAuth2Callback(OAuthCallback):
 76    """OpenIDConnect OAuth2 Callback"""
 77
 78    client_class = OpenIDConnectClient
 79
 80    def get_user_id(self, info: dict[str, str]) -> str:
 81        return str(info.get("sub") or info.get("id"))
 82
 83
 84@registry.register()
 85class OpenIDConnectType(SourceType):
 86    """OpenIDConnect Type definition"""
 87
 88    callback_view = OpenIDConnectOAuth2Callback
 89    redirect_view = OpenIDConnectOAuthRedirect
 90    verbose_name = "OpenID Connect"
 91    name = "openidconnect"
 92
 93    urls_customizable = True
 94    requires_client_secret = False
 95
 96    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
 97        return {
 98            "username": info.get("nickname", info.get("preferred_username")),
 99            "email": info.get("email"),
100            "name": info.get("name"),
101            "groups": info.get("groups", []),
102        }
class OpenIDConnectOAuthRedirect(authentik.sources.oauth.views.redirect.OAuthRedirect):
17class OpenIDConnectOAuthRedirect(OAuthRedirect):
18    """OpenIDConnect OAuth2 Redirect"""
19
20    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
21        return {
22            "scope": ["openid", "email", "profile"],
23        }

OpenIDConnect OAuth2 Redirect

def get_additional_parameters(self, source: authentik.sources.oauth.models.OAuthSource):
20    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
21        return {
22            "scope": ["openid", "email", "profile"],
23        }

Return additional redirect parameters for this source.

26class OpenIDConnectClient(UserprofileHeaderAuthClient):
27    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
28        args = super().get_access_token_args(callback, code)
29        client_id = self.get_client_id()
30        client_secret = self.get_client_secret()
31        if self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.POST_BODY:
32            args["client_id"] = client_id
33            if client_secret:
34                args["client_secret"] = client_secret
35        elif client_secret:
36            # Basic auth, credentials are sent in the header
37            args.pop("client_id", None)
38            args.pop("client_secret", None)
39        return args
40
41    def get_access_token_auth(self) -> AuthBase | None:
42        client_secret = self.get_client_secret()
43        if (
44            self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.BASIC_AUTH
45            and client_secret
46        ):
47            return HTTPBasicAuth(self.get_client_id(), client_secret)
48        return None
49
50    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
51        profile = super().get_profile_info(token)
52        if profile:
53            return profile
54        if "id_token" not in token:
55            self.logger.warning("no id_token given")
56            return None
57        id_token = token["id_token"]
58        try:
59            raw = get_unverified_header(id_token)
60            jwk = [
61                key for key in self.source.oidc_jwks.get("keys", []) if key.get("kid") == raw["kid"]
62            ][0]
63            key, _ = key_from_jwk(jwk)
64            return decode(
65                id_token,
66                key=key,
67                algorithms=[raw["alg"]],
68                audience=self.get_client_id(),
69                options={"verify_iss": False},
70            )
71        except (PyJWTError, IndexError, ValueError) as exc:
72            self.logger.warning("Failed to decode id_token", exc=exc)
73            return None

OAuth client which only sends authentication via header, not querystring

def get_access_token_args(self, callback: str, code: str) -> dict[str, typing.Any]:
27    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
28        args = super().get_access_token_args(callback, code)
29        client_id = self.get_client_id()
30        client_secret = self.get_client_secret()
31        if self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.POST_BODY:
32            args["client_id"] = client_id
33            if client_secret:
34                args["client_secret"] = client_secret
35        elif client_secret:
36            # Basic auth, credentials are sent in the header
37            args.pop("client_id", None)
38            args.pop("client_secret", None)
39        return args
def get_access_token_auth(self) -> requests.auth.AuthBase | None:
41    def get_access_token_auth(self) -> AuthBase | None:
42        client_secret = self.get_client_secret()
43        if (
44            self.source.authorization_code_auth_method == AuthorizationCodeAuthMethod.BASIC_AUTH
45            and client_secret
46        ):
47            return HTTPBasicAuth(self.get_client_id(), client_secret)
48        return None
def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
50    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
51        profile = super().get_profile_info(token)
52        if profile:
53            return profile
54        if "id_token" not in token:
55            self.logger.warning("no id_token given")
56            return None
57        id_token = token["id_token"]
58        try:
59            raw = get_unverified_header(id_token)
60            jwk = [
61                key for key in self.source.oidc_jwks.get("keys", []) if key.get("kid") == raw["kid"]
62            ][0]
63            key, _ = key_from_jwk(jwk)
64            return decode(
65                id_token,
66                key=key,
67                algorithms=[raw["alg"]],
68                audience=self.get_client_id(),
69                options={"verify_iss": False},
70            )
71        except (PyJWTError, IndexError, ValueError) as exc:
72            self.logger.warning("Failed to decode id_token", exc=exc)
73            return None

Fetch user profile information.

class OpenIDConnectOAuth2Callback(authentik.sources.oauth.views.callback.OAuthCallback):
76class OpenIDConnectOAuth2Callback(OAuthCallback):
77    """OpenIDConnect OAuth2 Callback"""
78
79    client_class = OpenIDConnectClient
80
81    def get_user_id(self, info: dict[str, str]) -> str:
82        return str(info.get("sub") or info.get("id"))

OpenIDConnect OAuth2 Callback

client_class = <class 'OpenIDConnectClient'>
def get_user_id(self, info: dict[str, str]) -> str:
81    def get_user_id(self, info: dict[str, str]) -> str:
82        return str(info.get("sub") or info.get("id"))

Return unique identifier from the profile info.

@registry.register()
class OpenIDConnectType(authentik.sources.oauth.types.registry.SourceType):
 85@registry.register()
 86class OpenIDConnectType(SourceType):
 87    """OpenIDConnect Type definition"""
 88
 89    callback_view = OpenIDConnectOAuth2Callback
 90    redirect_view = OpenIDConnectOAuthRedirect
 91    verbose_name = "OpenID Connect"
 92    name = "openidconnect"
 93
 94    urls_customizable = True
 95    requires_client_secret = False
 96
 97    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
 98        return {
 99            "username": info.get("nickname", info.get("preferred_username")),
100            "email": info.get("email"),
101            "name": info.get("name"),
102            "groups": info.get("groups", []),
103        }

OpenIDConnect Type definition

callback_view = <class 'OpenIDConnectOAuth2Callback'>
redirect_view = <class 'OpenIDConnectOAuthRedirect'>
verbose_name = 'OpenID Connect'
name = 'openidconnect'
urls_customizable = True
requires_client_secret = False
def get_base_user_properties(self, info: dict[str, typing.Any], **kwargs) -> dict[str, typing.Any]:
 97    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
 98        return {
 99            "username": info.get("nickname", info.get("preferred_username")),
100            "email": info.get("email"),
101            "name": info.get("name"),
102            "groups": info.get("groups", []),
103        }

Get base user properties for enrollment/update