authentik.enterprise.endpoints.connectors.agent.views.apple_authorize
1from datetime import timedelta 2 3from django.http import ( 4 Http404, 5 HttpRequest, 6 HttpResponse, 7 HttpResponseBadRequest, 8 JsonResponse, 9) 10from django.shortcuts import get_object_or_404 11from django.urls import reverse 12from django.utils.crypto import get_random_string 13from django.utils.decorators import method_decorator 14from django.utils.http import urlencode 15from django.utils.timezone import now 16from django.views import View 17from django.views.decorators.csrf import csrf_exempt 18from jwt import PyJWTError, decode, get_unverified_header 19from structlog.stdlib import get_logger 20 21from authentik.common.oauth.constants import QS_LOGIN_HINT 22from authentik.endpoints.connectors.agent.auth import check_device_policies 23from authentik.endpoints.connectors.agent.models import ( 24 AgentConnector, 25 AgentDeviceConnection, 26 AppleAuthorizationCode, 27) 28from authentik.enterprise.license import LicenseKey 29from authentik.enterprise.policy import EnterprisePolicyAccessView 30from authentik.flows.exceptions import FlowNonApplicableException 31from authentik.flows.models import in_memory_stage 32from authentik.flows.planner import FlowPlanner 33from authentik.flows.stage import PLAN_CONTEXT_PENDING_USER_IDENTIFIER, StageView 34from authentik.flows.views.executor import SESSION_KEY_POST 35from authentik.providers.oauth2.utils import HttpResponseRedirectScheme 36 37LOGGER = get_logger() 38 39PLAN_CONTEXT_PSSO = "goauthentik.io/endpoints/connectors/agent/psso" 40REDIRECT_URI = "com.apple.PlatformSSO://callback" 41 42 43class AppleAuthorizePreauthView(View): 44 """Platform SSO federation pre-authentication discovery endpoint, called before Platform 45 SSO loads the authorization web view. This is the only point in the flow that isn't a 46 plain unauthenticated request, so the `state` Platform SSO validates on the callback is 47 generated here and threaded through by AppleAuthorizeView. 48 https://developer.apple.com/documentation/authenticationservices/implementing-web-based-authentication 49 """ 50 51 def get(self, request: HttpRequest, connector_uuid: str) -> HttpResponse: 52 if not LicenseKey.get_total().status().is_valid: 53 return HttpResponseBadRequest("Enterprise required to access this feature.") 54 params = {"state": get_random_string(32), "redirect_uri": REDIRECT_URI} 55 if login_hint := request.GET.get("user"): 56 params[QS_LOGIN_HINT] = login_hint 57 url = request.build_absolute_uri( 58 reverse( 59 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 60 kwargs={"connector_uuid": connector_uuid}, 61 ) 62 ) 63 return JsonResponse( 64 { 65 "authorization_url": f"{url}?{urlencode(params)}", 66 # Platform SSO only sends the device-signed request object to the authorization 67 # endpoint when the pre-authentication response includes this. 68 "authorizationRequest": { 69 "client_id": str(connector_uuid), 70 "redirect_uri": REDIRECT_URI, 71 "response_type": "code", 72 "scope": "openid profile email", 73 "state": params["state"], 74 }, 75 } 76 ) 77 78 79@method_decorator(csrf_exempt, name="dispatch") 80class AppleAuthorizeView(EnterprisePolicyAccessView): 81 """Platform SSO federation authorization endpoint, exchanges a browser-based login for an 82 authorization code which the device redeems at the token endpoint.""" 83 84 connector: AgentConnector 85 device_connection: AgentDeviceConnection 86 87 def resolve_provider_application(self): 88 self.connector = get_object_or_404(AgentConnector, pk=self.kwargs["connector_uuid"]) 89 self.device_connection = self.resolve_device_connection() 90 91 def resolve_device_connection(self) -> AgentDeviceConnection: 92 """dynamicOpenID federation POSTs a device-signed JWT ('request' form field) next to the 93 same query string a plain GET would carry; it identifies the device the request came 94 from. Only dynamicOpenID is supported, plain federation carries no device identity and 95 could neither be policy-checked nor bound to the authorization code it receives.""" 96 # When the user isn't logged in yet, the POST data is kept in the session while they 97 # authenticate, and they come back to this view with a GET 98 post_data = self.request.POST or self.request.session.get(SESSION_KEY_POST, {}) 99 assertion = post_data.get("request") 100 if not assertion: 101 LOGGER.warning("Platform SSO authorization request without a request object") 102 raise Http404 103 try: 104 connection = ( 105 AgentDeviceConnection.objects.filter( 106 apple_sign_key_id=get_unverified_header(assertion)["kid"], 107 connector=self.connector, 108 ) 109 .select_related("device") 110 .first() 111 ) 112 if not connection: 113 raise Http404 114 decode( 115 assertion, 116 connection.apple_signing_key, 117 algorithms=["ES256"], 118 options={"verify_aud": False}, 119 ) 120 except (PyJWTError, KeyError) as exc: 121 LOGGER.warning("Invalid Platform SSO authorization request JWT", exc=exc) 122 raise Http404 from exc 123 return connection 124 125 def user_has_access(self, user=None, pbm=None): 126 result = self.check_license() 127 if not result.passing: 128 return result 129 return check_device_policies( 130 self.device_connection.device, user or self.request.user, self.request 131 ) 132 133 def modify_flow_context(self, flow, context): 134 if QS_LOGIN_HINT in self.request.GET: 135 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = self.request.GET[QS_LOGIN_HINT] 136 return super().modify_flow_context(flow, context) 137 138 # dynamicOpenID POSTs the signed request object alongside the same query string a plain 139 # GET would carry, so the parameters are still read from request.GET. 140 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 141 if request.GET.get("redirect_uri") != REDIRECT_URI: 142 return HttpResponseBadRequest("Invalid redirect_uri") 143 if not self.connector.authorization_flow: 144 return HttpResponseBadRequest("No authorization flow configured") 145 146 planner = FlowPlanner(self.connector.authorization_flow) 147 planner.allow_empty_flows = True 148 context = { 149 PLAN_CONTEXT_PSSO: { 150 "state": request.GET.get("state", ""), 151 "connector": self.connector, 152 "device_connection": self.device_connection, 153 "scope": request.GET.get("scope", "openid profile email"), 154 } 155 } 156 if login_hint := request.GET.get(QS_LOGIN_HINT): 157 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = login_hint 158 try: 159 plan = planner.plan(request, context) 160 except FlowNonApplicableException: 161 return self.handle_no_permission_authenticated() 162 163 plan.append_stage(in_memory_stage(PSSOAuthFulfillmentStage)) 164 request.session.pop(SESSION_KEY_POST, None) 165 return plan.to_redirect(request, self.connector.authorization_flow) 166 167 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 168 """Return from the authentication flow, with the request object in the session""" 169 return self.post(request, *args, **kwargs) 170 171 172class PSSOAuthFulfillmentStage(StageView): 173 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 174 psso: dict = self.executor.plan.context.pop(PLAN_CONTEXT_PSSO) 175 auth_code = AppleAuthorizationCode.objects.create( 176 user=request.user, 177 connector=psso["connector"], 178 device_connection=psso["device_connection"], 179 state=psso["state"], 180 scope=psso["scope"], 181 expires=now() + timedelta(minutes=5), 182 ) 183 params = {"code": auth_code.code} 184 if psso["state"]: 185 params["state"] = psso["state"] 186 return HttpResponseRedirectScheme( 187 f"{REDIRECT_URI}?{urlencode(params)}", 188 allowed_schemes=["com.apple.platformsso"], 189 )
44class AppleAuthorizePreauthView(View): 45 """Platform SSO federation pre-authentication discovery endpoint, called before Platform 46 SSO loads the authorization web view. This is the only point in the flow that isn't a 47 plain unauthenticated request, so the `state` Platform SSO validates on the callback is 48 generated here and threaded through by AppleAuthorizeView. 49 https://developer.apple.com/documentation/authenticationservices/implementing-web-based-authentication 50 """ 51 52 def get(self, request: HttpRequest, connector_uuid: str) -> HttpResponse: 53 if not LicenseKey.get_total().status().is_valid: 54 return HttpResponseBadRequest("Enterprise required to access this feature.") 55 params = {"state": get_random_string(32), "redirect_uri": REDIRECT_URI} 56 if login_hint := request.GET.get("user"): 57 params[QS_LOGIN_HINT] = login_hint 58 url = request.build_absolute_uri( 59 reverse( 60 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 61 kwargs={"connector_uuid": connector_uuid}, 62 ) 63 ) 64 return JsonResponse( 65 { 66 "authorization_url": f"{url}?{urlencode(params)}", 67 # Platform SSO only sends the device-signed request object to the authorization 68 # endpoint when the pre-authentication response includes this. 69 "authorizationRequest": { 70 "client_id": str(connector_uuid), 71 "redirect_uri": REDIRECT_URI, 72 "response_type": "code", 73 "scope": "openid profile email", 74 "state": params["state"], 75 }, 76 } 77 )
Platform SSO federation pre-authentication discovery endpoint, called before Platform
SSO loads the authorization web view. This is the only point in the flow that isn't a
plain unauthenticated request, so the state Platform SSO validates on the callback is
generated here and threaded through by AppleAuthorizeView.
https://developer.apple.com/documentation/authenticationservices/implementing-web-based-authentication
52 def get(self, request: HttpRequest, connector_uuid: str) -> HttpResponse: 53 if not LicenseKey.get_total().status().is_valid: 54 return HttpResponseBadRequest("Enterprise required to access this feature.") 55 params = {"state": get_random_string(32), "redirect_uri": REDIRECT_URI} 56 if login_hint := request.GET.get("user"): 57 params[QS_LOGIN_HINT] = login_hint 58 url = request.build_absolute_uri( 59 reverse( 60 "authentik_enterprise_endpoints_connectors_agent:psso-authorize", 61 kwargs={"connector_uuid": connector_uuid}, 62 ) 63 ) 64 return JsonResponse( 65 { 66 "authorization_url": f"{url}?{urlencode(params)}", 67 # Platform SSO only sends the device-signed request object to the authorization 68 # endpoint when the pre-authentication response includes this. 69 "authorizationRequest": { 70 "client_id": str(connector_uuid), 71 "redirect_uri": REDIRECT_URI, 72 "response_type": "code", 73 "scope": "openid profile email", 74 "state": params["state"], 75 }, 76 } 77 )
80@method_decorator(csrf_exempt, name="dispatch") 81class AppleAuthorizeView(EnterprisePolicyAccessView): 82 """Platform SSO federation authorization endpoint, exchanges a browser-based login for an 83 authorization code which the device redeems at the token endpoint.""" 84 85 connector: AgentConnector 86 device_connection: AgentDeviceConnection 87 88 def resolve_provider_application(self): 89 self.connector = get_object_or_404(AgentConnector, pk=self.kwargs["connector_uuid"]) 90 self.device_connection = self.resolve_device_connection() 91 92 def resolve_device_connection(self) -> AgentDeviceConnection: 93 """dynamicOpenID federation POSTs a device-signed JWT ('request' form field) next to the 94 same query string a plain GET would carry; it identifies the device the request came 95 from. Only dynamicOpenID is supported, plain federation carries no device identity and 96 could neither be policy-checked nor bound to the authorization code it receives.""" 97 # When the user isn't logged in yet, the POST data is kept in the session while they 98 # authenticate, and they come back to this view with a GET 99 post_data = self.request.POST or self.request.session.get(SESSION_KEY_POST, {}) 100 assertion = post_data.get("request") 101 if not assertion: 102 LOGGER.warning("Platform SSO authorization request without a request object") 103 raise Http404 104 try: 105 connection = ( 106 AgentDeviceConnection.objects.filter( 107 apple_sign_key_id=get_unverified_header(assertion)["kid"], 108 connector=self.connector, 109 ) 110 .select_related("device") 111 .first() 112 ) 113 if not connection: 114 raise Http404 115 decode( 116 assertion, 117 connection.apple_signing_key, 118 algorithms=["ES256"], 119 options={"verify_aud": False}, 120 ) 121 except (PyJWTError, KeyError) as exc: 122 LOGGER.warning("Invalid Platform SSO authorization request JWT", exc=exc) 123 raise Http404 from exc 124 return connection 125 126 def user_has_access(self, user=None, pbm=None): 127 result = self.check_license() 128 if not result.passing: 129 return result 130 return check_device_policies( 131 self.device_connection.device, user or self.request.user, self.request 132 ) 133 134 def modify_flow_context(self, flow, context): 135 if QS_LOGIN_HINT in self.request.GET: 136 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = self.request.GET[QS_LOGIN_HINT] 137 return super().modify_flow_context(flow, context) 138 139 # dynamicOpenID POSTs the signed request object alongside the same query string a plain 140 # GET would carry, so the parameters are still read from request.GET. 141 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 142 if request.GET.get("redirect_uri") != REDIRECT_URI: 143 return HttpResponseBadRequest("Invalid redirect_uri") 144 if not self.connector.authorization_flow: 145 return HttpResponseBadRequest("No authorization flow configured") 146 147 planner = FlowPlanner(self.connector.authorization_flow) 148 planner.allow_empty_flows = True 149 context = { 150 PLAN_CONTEXT_PSSO: { 151 "state": request.GET.get("state", ""), 152 "connector": self.connector, 153 "device_connection": self.device_connection, 154 "scope": request.GET.get("scope", "openid profile email"), 155 } 156 } 157 if login_hint := request.GET.get(QS_LOGIN_HINT): 158 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = login_hint 159 try: 160 plan = planner.plan(request, context) 161 except FlowNonApplicableException: 162 return self.handle_no_permission_authenticated() 163 164 plan.append_stage(in_memory_stage(PSSOAuthFulfillmentStage)) 165 request.session.pop(SESSION_KEY_POST, None) 166 return plan.to_redirect(request, self.connector.authorization_flow) 167 168 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 169 """Return from the authentication flow, with the request object in the session""" 170 return self.post(request, *args, **kwargs)
Platform SSO federation authorization endpoint, exchanges a browser-based login for an authorization code which the device redeems at the token endpoint.
88 def resolve_provider_application(self): 89 self.connector = get_object_or_404(AgentConnector, pk=self.kwargs["connector_uuid"]) 90 self.device_connection = self.resolve_device_connection()
Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal AccessDenied view to be shown. An Http404 exception is not caught, and will return directly
92 def resolve_device_connection(self) -> AgentDeviceConnection: 93 """dynamicOpenID federation POSTs a device-signed JWT ('request' form field) next to the 94 same query string a plain GET would carry; it identifies the device the request came 95 from. Only dynamicOpenID is supported, plain federation carries no device identity and 96 could neither be policy-checked nor bound to the authorization code it receives.""" 97 # When the user isn't logged in yet, the POST data is kept in the session while they 98 # authenticate, and they come back to this view with a GET 99 post_data = self.request.POST or self.request.session.get(SESSION_KEY_POST, {}) 100 assertion = post_data.get("request") 101 if not assertion: 102 LOGGER.warning("Platform SSO authorization request without a request object") 103 raise Http404 104 try: 105 connection = ( 106 AgentDeviceConnection.objects.filter( 107 apple_sign_key_id=get_unverified_header(assertion)["kid"], 108 connector=self.connector, 109 ) 110 .select_related("device") 111 .first() 112 ) 113 if not connection: 114 raise Http404 115 decode( 116 assertion, 117 connection.apple_signing_key, 118 algorithms=["ES256"], 119 options={"verify_aud": False}, 120 ) 121 except (PyJWTError, KeyError) as exc: 122 LOGGER.warning("Invalid Platform SSO authorization request JWT", exc=exc) 123 raise Http404 from exc 124 return connection
dynamicOpenID federation POSTs a device-signed JWT ('request' form field) next to the same query string a plain GET would carry; it identifies the device the request came from. Only dynamicOpenID is supported, plain federation carries no device identity and could neither be policy-checked nor bound to the authorization code it receives.
126 def user_has_access(self, user=None, pbm=None): 127 result = self.check_license() 128 if not result.passing: 129 return result 130 return check_device_policies( 131 self.device_connection.device, user or self.request.user, self.request 132 )
Check if user has access to application.
134 def modify_flow_context(self, flow, context): 135 if QS_LOGIN_HINT in self.request.GET: 136 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = self.request.GET[QS_LOGIN_HINT] 137 return super().modify_flow_context(flow, context)
optionally modify the flow context which is used for the authentication flow
141 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 142 if request.GET.get("redirect_uri") != REDIRECT_URI: 143 return HttpResponseBadRequest("Invalid redirect_uri") 144 if not self.connector.authorization_flow: 145 return HttpResponseBadRequest("No authorization flow configured") 146 147 planner = FlowPlanner(self.connector.authorization_flow) 148 planner.allow_empty_flows = True 149 context = { 150 PLAN_CONTEXT_PSSO: { 151 "state": request.GET.get("state", ""), 152 "connector": self.connector, 153 "device_connection": self.device_connection, 154 "scope": request.GET.get("scope", "openid profile email"), 155 } 156 } 157 if login_hint := request.GET.get(QS_LOGIN_HINT): 158 context[PLAN_CONTEXT_PENDING_USER_IDENTIFIER] = login_hint 159 try: 160 plan = planner.plan(request, context) 161 except FlowNonApplicableException: 162 return self.handle_no_permission_authenticated() 163 164 plan.append_stage(in_memory_stage(PSSOAuthFulfillmentStage)) 165 request.session.pop(SESSION_KEY_POST, None) 166 return plan.to_redirect(request, self.connector.authorization_flow)
168 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 169 """Return from the authentication flow, with the request object in the session""" 170 return self.post(request, *args, **kwargs)
Return from the authentication flow, with the request object in the session
68 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 69 try: 70 self.pre_permission_check() 71 except RequestValidationError as exc: 72 if exc.response: 73 return exc.response 74 return self.handle_no_permission() 75 try: 76 self.resolve_provider_application() 77 except (Application.DoesNotExist, Provider.DoesNotExist) as exc: 78 LOGGER.warning("failed to resolve application", exc=exc) 79 return self.handle_no_permission_authenticated( 80 PolicyResult(False, _("Failed to resolve application")) 81 ) 82 # Check if user is unauthenticated, so we pass the application 83 # for the identification stage 84 if not request.user.is_authenticated: 85 return self.handle_no_permission() 86 # Check permissions 87 result = self.user_has_access() 88 if not result.passing: 89 return self.handle_no_permission_authenticated(result) 90 return super().dispatch(request, *args, **kwargs)
173class PSSOAuthFulfillmentStage(StageView): 174 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 175 psso: dict = self.executor.plan.context.pop(PLAN_CONTEXT_PSSO) 176 auth_code = AppleAuthorizationCode.objects.create( 177 user=request.user, 178 connector=psso["connector"], 179 device_connection=psso["device_connection"], 180 state=psso["state"], 181 scope=psso["scope"], 182 expires=now() + timedelta(minutes=5), 183 ) 184 params = {"code": auth_code.code} 185 if psso["state"]: 186 params["state"] = psso["state"] 187 return HttpResponseRedirectScheme( 188 f"{REDIRECT_URI}?{urlencode(params)}", 189 allowed_schemes=["com.apple.platformsso"], 190 )
Abstract Stage
174 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 175 psso: dict = self.executor.plan.context.pop(PLAN_CONTEXT_PSSO) 176 auth_code = AppleAuthorizationCode.objects.create( 177 user=request.user, 178 connector=psso["connector"], 179 device_connection=psso["device_connection"], 180 state=psso["state"], 181 scope=psso["scope"], 182 expires=now() + timedelta(minutes=5), 183 ) 184 params = {"code": auth_code.code} 185 if psso["state"]: 186 params["state"] = psso["state"] 187 return HttpResponseRedirectScheme( 188 f"{REDIRECT_URI}?{urlencode(params)}", 189 allowed_schemes=["com.apple.platformsso"], 190 )