authentik.sources.oauth.types.apple

Apple OAuth Views

  1"""Apple OAuth Views"""
  2
  3from time import time
  4from typing import Any
  5
  6from django.http.request import HttpRequest
  7from django.urls.base import reverse
  8from jwt import encode
  9from rest_framework.fields import CharField
 10
 11from authentik.flows.challenge import Challenge, ChallengeResponse
 12from authentik.sources.oauth.models import AuthorizationCodeAuthMethod, OAuthSource
 13from authentik.sources.oauth.types.oidc import OpenIDConnectClient
 14from authentik.sources.oauth.types.registry import SourceType, registry
 15from authentik.sources.oauth.views.callback import OAuthCallback
 16from authentik.sources.oauth.views.redirect import OAuthRedirect
 17from authentik.stages.identification.stage import LoginChallengeMixin
 18
 19APPLE_CLIENT_ID_PARTS = 3
 20
 21
 22class AppleLoginChallenge(LoginChallengeMixin, Challenge):
 23    """Special challenge for apple-native authentication flow, which happens on the client."""
 24
 25    client_id = CharField()
 26    component = CharField(default="ak-source-oauth-apple")
 27    scope = CharField()
 28    redirect_uri = CharField()
 29    state = CharField()
 30
 31
 32class AppleChallengeResponse(ChallengeResponse):
 33    """Pseudo class for apple response"""
 34
 35    component = CharField(default="ak-source-oauth-apple")
 36
 37
 38class AppleOAuthClient(OpenIDConnectClient):
 39    """Apple OAuth2 client"""
 40
 41    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
 42        args = super().get_access_token_args(callback, code)
 43        args["client_id"] = self.get_client_id()
 44        args["client_secret"] = self.get_client_secret()
 45        return args
 46
 47    def get_access_token_auth(self) -> None:
 48        return None
 49
 50    def get_client_id(self) -> str:
 51        parts: list[str] = self.source.consumer_key.split(";")
 52        if len(parts) < APPLE_CLIENT_ID_PARTS:
 53            return self.source.consumer_key
 54        return parts[0].strip()
 55
 56    def get_client_secret(self) -> str:
 57        now = time()
 58        parts: list[str] = self.source.consumer_key.split(";")
 59        if len(parts) < APPLE_CLIENT_ID_PARTS:
 60            raise ValueError(
 61                "Apple Source client_id should be formatted like "
 62                "services_id_identifier;apple_team_id;key_id"
 63            )
 64        self.logger.debug("got values from client_id", team=parts[1], kid=parts[2])
 65        payload = {
 66            "iss": parts[1].strip(),
 67            "iat": now,
 68            "exp": now + 86400 * 180,
 69            "aud": "https://appleid.apple.com",
 70            "sub": parts[0].strip(),
 71        }
 72        jwt = encode(payload, self.source.consumer_secret, "ES256", {"kid": parts[2].strip()})
 73        self.logger.debug("signing payload as secret key", payload=payload, jwt=jwt)
 74        return jwt
 75
 76
 77class AppleOAuthRedirect(OAuthRedirect):
 78    """Apple OAuth2 Redirect"""
 79
 80    client_class = AppleOAuthClient
 81
 82    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
 83        return {
 84            "scope": ["name", "email"],
 85            "response_mode": "form_post",
 86        }
 87
 88
 89class AppleOAuth2Callback(OAuthCallback):
 90    """Apple OAuth2 Callback"""
 91
 92    client_class = AppleOAuthClient
 93
 94    def get_user_id(self, info: dict[str, Any]) -> str | None:
 95        return info["sub"]
 96
 97
 98@registry.register()
 99class AppleType(SourceType):
100    """Apple Type definition"""
101
102    callback_view = AppleOAuth2Callback
103    redirect_view = AppleOAuthRedirect
104    verbose_name = "Apple"
105    name = "apple"
106
107    authorization_url = "https://appleid.apple.com/auth/authorize"
108    access_token_url = "https://appleid.apple.com/auth/token"  # nosec
109    profile_url = ""
110    oidc_well_known_url = "https://appleid.apple.com/.well-known/openid-configuration"
111    oidc_jwks_url = "https://appleid.apple.com/auth/keys"
112
113    authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
114
115    def login_challenge(self, source: OAuthSource, request: HttpRequest) -> Challenge:
116        """Pre-general all the things required for the JS SDK"""
117        apple_client = AppleOAuthClient(
118            source,
119            request,
120            callback=reverse(
121                "authentik_sources_oauth:oauth-client-callback",
122                kwargs={"source_slug": source.slug},
123            ),
124        )
125        args = apple_client.get_redirect_args()
126        return AppleLoginChallenge(
127            data={
128                "client_id": apple_client.get_client_id(),
129                "scope": "name email",
130                "redirect_uri": args["redirect_uri"],
131                "state": args["state"],
132            }
133        )
134
135    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
136        return {
137            "email": info.get("email"),
138            "name": info.get("name"),
139        }
APPLE_CLIENT_ID_PARTS = 3
23class AppleLoginChallenge(LoginChallengeMixin, Challenge):
24    """Special challenge for apple-native authentication flow, which happens on the client."""
25
26    client_id = CharField()
27    component = CharField(default="ak-source-oauth-apple")
28    scope = CharField()
29    redirect_uri = CharField()
30    state = CharField()

Special challenge for apple-native authentication flow, which happens on the client.

client_id
component
scope
redirect_uri
state
class AppleChallengeResponse(authentik.flows.challenge.ChallengeResponse):
33class AppleChallengeResponse(ChallengeResponse):
34    """Pseudo class for apple response"""
35
36    component = CharField(default="ak-source-oauth-apple")

Pseudo class for apple response

component
class AppleOAuthClient(authentik.sources.oauth.types.oidc.OpenIDConnectClient):
39class AppleOAuthClient(OpenIDConnectClient):
40    """Apple OAuth2 client"""
41
42    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
43        args = super().get_access_token_args(callback, code)
44        args["client_id"] = self.get_client_id()
45        args["client_secret"] = self.get_client_secret()
46        return args
47
48    def get_access_token_auth(self) -> None:
49        return None
50
51    def get_client_id(self) -> str:
52        parts: list[str] = self.source.consumer_key.split(";")
53        if len(parts) < APPLE_CLIENT_ID_PARTS:
54            return self.source.consumer_key
55        return parts[0].strip()
56
57    def get_client_secret(self) -> str:
58        now = time()
59        parts: list[str] = self.source.consumer_key.split(";")
60        if len(parts) < APPLE_CLIENT_ID_PARTS:
61            raise ValueError(
62                "Apple Source client_id should be formatted like "
63                "services_id_identifier;apple_team_id;key_id"
64            )
65        self.logger.debug("got values from client_id", team=parts[1], kid=parts[2])
66        payload = {
67            "iss": parts[1].strip(),
68            "iat": now,
69            "exp": now + 86400 * 180,
70            "aud": "https://appleid.apple.com",
71            "sub": parts[0].strip(),
72        }
73        jwt = encode(payload, self.source.consumer_secret, "ES256", {"kid": parts[2].strip()})
74        self.logger.debug("signing payload as secret key", payload=payload, jwt=jwt)
75        return jwt

Apple OAuth2 client

def get_access_token_args(self, callback: str, code: str) -> dict[str, typing.Any]:
42    def get_access_token_args(self, callback: str, code: str) -> dict[str, Any]:
43        args = super().get_access_token_args(callback, code)
44        args["client_id"] = self.get_client_id()
45        args["client_secret"] = self.get_client_secret()
46        return args
def get_access_token_auth(self) -> None:
48    def get_access_token_auth(self) -> None:
49        return None
def get_client_id(self) -> str:
51    def get_client_id(self) -> str:
52        parts: list[str] = self.source.consumer_key.split(";")
53        if len(parts) < APPLE_CLIENT_ID_PARTS:
54            return self.source.consumer_key
55        return parts[0].strip()

Get client id

def get_client_secret(self) -> str:
57    def get_client_secret(self) -> str:
58        now = time()
59        parts: list[str] = self.source.consumer_key.split(";")
60        if len(parts) < APPLE_CLIENT_ID_PARTS:
61            raise ValueError(
62                "Apple Source client_id should be formatted like "
63                "services_id_identifier;apple_team_id;key_id"
64            )
65        self.logger.debug("got values from client_id", team=parts[1], kid=parts[2])
66        payload = {
67            "iss": parts[1].strip(),
68            "iat": now,
69            "exp": now + 86400 * 180,
70            "aud": "https://appleid.apple.com",
71            "sub": parts[0].strip(),
72        }
73        jwt = encode(payload, self.source.consumer_secret, "ES256", {"kid": parts[2].strip()})
74        self.logger.debug("signing payload as secret key", payload=payload, jwt=jwt)
75        return jwt

Get client secret

class AppleOAuthRedirect(authentik.sources.oauth.views.redirect.OAuthRedirect):
78class AppleOAuthRedirect(OAuthRedirect):
79    """Apple OAuth2 Redirect"""
80
81    client_class = AppleOAuthClient
82
83    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
84        return {
85            "scope": ["name", "email"],
86            "response_mode": "form_post",
87        }

Apple OAuth2 Redirect

client_class = <class 'AppleOAuthClient'>
def get_additional_parameters(self, source: authentik.sources.oauth.models.OAuthSource):
83    def get_additional_parameters(self, source: OAuthSource):  # pragma: no cover
84        return {
85            "scope": ["name", "email"],
86            "response_mode": "form_post",
87        }

Return additional redirect parameters for this source.

class AppleOAuth2Callback(authentik.sources.oauth.views.callback.OAuthCallback):
90class AppleOAuth2Callback(OAuthCallback):
91    """Apple OAuth2 Callback"""
92
93    client_class = AppleOAuthClient
94
95    def get_user_id(self, info: dict[str, Any]) -> str | None:
96        return info["sub"]

Apple OAuth2 Callback

client_class = <class 'AppleOAuthClient'>
def get_user_id(self, info: dict[str, typing.Any]) -> str | None:
95    def get_user_id(self, info: dict[str, Any]) -> str | None:
96        return info["sub"]

Return unique identifier from the profile info.

@registry.register()
class AppleType(authentik.sources.oauth.types.registry.SourceType):
 99@registry.register()
100class AppleType(SourceType):
101    """Apple Type definition"""
102
103    callback_view = AppleOAuth2Callback
104    redirect_view = AppleOAuthRedirect
105    verbose_name = "Apple"
106    name = "apple"
107
108    authorization_url = "https://appleid.apple.com/auth/authorize"
109    access_token_url = "https://appleid.apple.com/auth/token"  # nosec
110    profile_url = ""
111    oidc_well_known_url = "https://appleid.apple.com/.well-known/openid-configuration"
112    oidc_jwks_url = "https://appleid.apple.com/auth/keys"
113
114    authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
115
116    def login_challenge(self, source: OAuthSource, request: HttpRequest) -> Challenge:
117        """Pre-general all the things required for the JS SDK"""
118        apple_client = AppleOAuthClient(
119            source,
120            request,
121            callback=reverse(
122                "authentik_sources_oauth:oauth-client-callback",
123                kwargs={"source_slug": source.slug},
124            ),
125        )
126        args = apple_client.get_redirect_args()
127        return AppleLoginChallenge(
128            data={
129                "client_id": apple_client.get_client_id(),
130                "scope": "name email",
131                "redirect_uri": args["redirect_uri"],
132                "state": args["state"],
133            }
134        )
135
136    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
137        return {
138            "email": info.get("email"),
139            "name": info.get("name"),
140        }

Apple Type definition

callback_view = <class 'AppleOAuth2Callback'>
redirect_view = <class 'AppleOAuthRedirect'>
verbose_name = 'Apple'
name = 'apple'
authorization_url = 'https://appleidauthentik.sources.oauth.types.apple.com/auth/authorize'
access_token_url = 'https://appleidauthentik.sources.oauth.types.apple.com/auth/token'
profile_url = ''
oidc_well_known_url = 'https://appleidauthentik.sources.oauth.types.apple.com/.well-known/openid-configuration'
oidc_jwks_url = 'https://appleidauthentik.sources.oauth.types.apple.com/auth/keys'
authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
def login_challenge( self, source: authentik.sources.oauth.models.OAuthSource, request: django.http.request.HttpRequest) -> authentik.flows.challenge.Challenge:
116    def login_challenge(self, source: OAuthSource, request: HttpRequest) -> Challenge:
117        """Pre-general all the things required for the JS SDK"""
118        apple_client = AppleOAuthClient(
119            source,
120            request,
121            callback=reverse(
122                "authentik_sources_oauth:oauth-client-callback",
123                kwargs={"source_slug": source.slug},
124            ),
125        )
126        args = apple_client.get_redirect_args()
127        return AppleLoginChallenge(
128            data={
129                "client_id": apple_client.get_client_id(),
130                "scope": "name email",
131                "redirect_uri": args["redirect_uri"],
132                "state": args["state"],
133            }
134        )

Pre-general all the things required for the JS SDK

def get_base_user_properties(self, info: dict[str, typing.Any], **kwargs) -> dict[str, typing.Any]:
136    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
137        return {
138            "email": info.get("email"),
139            "name": info.get("name"),
140        }

Get base user properties for enrollment/update