authentik.providers.oauth2.views.dcr
authentik OAuth2 Dynamic Client Registration (RFC 7591)
1"""authentik OAuth2 Dynamic Client Registration (RFC 7591)""" 2 3import json 4import time 5from typing import Any 6 7from django.db import transaction 8from django.http import HttpRequest, HttpResponse, JsonResponse 9from django.shortcuts import get_object_or_404 10from django.utils.decorators import method_decorator 11from django.utils.text import slugify 12from django.views import View 13from django.views.decorators.csrf import csrf_exempt 14from structlog.stdlib import get_logger 15 16from authentik.api.authentication import validate_auth 17from authentik.common.oauth.constants import SCOPE_AUTHENTIK_DCR 18from authentik.core.apps import AppAccessWithoutBindings 19from authentik.core.models import Application, User 20from authentik.lib.generators import generate_id 21from authentik.policies.engine import PolicyEngine 22from authentik.policies.models import PolicyBinding 23from authentik.providers.oauth2.models import ( 24 AccessToken, 25 ClientType, 26 GrantType, 27 OAuth2DynamicClientRegistration, 28 OAuth2Provider, 29 RedirectURI, 30 RedirectURIMatchingMode, 31 generate_client_secret, 32) 33 34LOGGER = get_logger() 35 36AUTH_METHOD_TO_CLIENT_TYPE = { 37 "client_secret_basic": ClientType.CONFIDENTIAL, 38 "client_secret_post": ClientType.CONFIDENTIAL, 39 "none": ClientType.PUBLIC, 40} 41 42 43def _dcr_error(error: str, description: str, status: int = 400) -> JsonResponse: 44 return JsonResponse({"error": error, "error_description": description}, status=status) 45 46 47@method_decorator(csrf_exempt, name="dispatch") 48class DynamicClientRegistrationView(View): 49 """RFC 7591 Dynamic Client Registration endpoint.""" 50 51 dcr: OAuth2DynamicClientRegistration 52 application: Application 53 provider: OAuth2Provider 54 55 def _authenticate_access_token(self, request: HttpRequest) -> AccessToken | None: 56 """Authenticate the request via a Bearer `AccessToken` carrying the 57 `goauthentik.io/oidc/dcr` scope, mirroring how `SCOPE_AUTHENTIK_API` 58 authenticates access to authentik's own API.""" 59 raw_token = validate_auth(request.headers.get("Authorization", "").encode()) 60 if not raw_token: 61 return None 62 access_token = AccessToken.objects.filter( 63 token=raw_token, _scope__icontains=SCOPE_AUTHENTIK_DCR 64 ).first() 65 if not access_token or SCOPE_AUTHENTIK_DCR not in access_token.scope: 66 return None 67 return access_token 68 69 def _check_policy_access(self, request: HttpRequest, user: User) -> bool: 70 engine = PolicyEngine(self.application, user, request) 71 engine.empty_result = AppAccessWithoutBindings.get() 72 engine.use_cache = False 73 engine.mode = self.application.policy_engine_mode 74 engine.build() 75 return engine.result.passing 76 77 def _unique_app_slug(self, base: str) -> str: 78 slug = slugify(base)[:200] or "client" 79 candidate = slug 80 counter = 1 81 while Application.objects.filter(slug=candidate).exists(): 82 candidate = f"{slug}-{counter}" 83 counter += 1 84 return candidate 85 86 @transaction.atomic 87 def post(self, request: HttpRequest, application_slug: str) -> HttpResponse: 88 # --- Access control ----------------------------------------------- 89 access_token = self._authenticate_access_token(request) 90 if access_token is None: 91 return _dcr_error( 92 "invalid_token", 93 "A valid access token with the " 94 f"'{SCOPE_AUTHENTIK_DCR}' scope is required to register clients.", 95 status=401, 96 ) 97 98 if not self._check_policy_access(request, access_token.user): 99 LOGGER.info("DCR registration rejected by policy", slug=application_slug) 100 return _dcr_error( 101 "access_denied", "Policy check failed for client registration.", status=403 102 ) 103 104 # --- Parse request body ------------------------------------------ 105 try: 106 metadata: dict[str, Any] = json.loads(request.body) 107 except json.JSONDecodeError, UnicodeDecodeError: 108 return _dcr_error("invalid_client_metadata", "Request body must be valid JSON.") 109 110 if not isinstance(metadata, dict): 111 return _dcr_error("invalid_client_metadata", "Request body must be a JSON object.") 112 113 raw_uris = metadata.get("redirect_uris") 114 if not raw_uris or not isinstance(raw_uris, list): 115 return _dcr_error( 116 "invalid_redirect_uri", "redirect_uris is required and must be a non-empty list." 117 ) 118 if not all(isinstance(u, str) for u in raw_uris): 119 return _dcr_error("invalid_redirect_uri", "All redirect_uris must be strings.") 120 121 redirect_uris = [ 122 RedirectURI(matching_mode=RedirectURIMatchingMode.STRICT, url=uri) for uri in raw_uris 123 ] 124 125 # --- Resolve settings -------------------------------------------- 126 auth_method = metadata.get("token_endpoint_auth_method", "client_secret_basic") 127 client_type = AUTH_METHOD_TO_CLIENT_TYPE.get(auth_method, ClientType.CONFIDENTIAL) 128 129 requested_grants = metadata.get("grant_types", [GrantType.AUTHORIZATION_CODE]) 130 if not isinstance(requested_grants, list): 131 return _dcr_error("invalid_client_metadata", "grant_types must be an array.") 132 if self.dcr.allowed_grant_types: 133 requested_grants = [g for g in requested_grants if g in self.dcr.allowed_grant_types] 134 grant_types = [g for g in requested_grants if g in GrantType.values] or [ 135 GrantType.AUTHORIZATION_CODE 136 ] 137 138 client_name = metadata.get("client_name", "") 139 140 # --- Create OAuth2Provider --------------------------------------- 141 provider = OAuth2Provider( 142 name=client_name or generate_id(), 143 client_id=generate_id(), 144 client_secret=generate_client_secret(), 145 client_type=client_type, 146 grant_types=grant_types, 147 authorization_flow=self.dcr.override_authorization_flow 148 or self.provider.authorization_flow, 149 invalidation_flow=self.dcr.override_invalidation_flow 150 or self.provider.invalidation_flow, 151 access_token_validity=self.dcr.access_token_validity 152 or self.provider.access_token_validity, 153 refresh_token_validity=self.dcr.refresh_token_validity 154 or self.provider.refresh_token_validity, 155 ) 156 provider.redirect_uris = redirect_uris 157 provider.save() 158 159 if self.dcr.override_property_mappings.exists(): 160 provider.property_mappings.set(self.dcr.override_property_mappings.all()) 161 else: 162 provider.property_mappings.set(self.provider.property_mappings.all()) 163 164 app_slug = self._unique_app_slug(client_name or provider.client_id) 165 app = Application.objects.create( 166 name=client_name or provider.client_id, 167 slug=app_slug, 168 provider=provider, 169 group=self.dcr.default_application_group, 170 policy_engine_mode=self.dcr.policy_engine_mode, 171 ) 172 bindings = PolicyBinding.objects.filter(target=self.dcr) 173 if not bindings.exists(): 174 bindings = PolicyBinding.objects.filter(target=self.application) 175 new_bindings = [] 176 for binding in bindings: 177 new_bindings.append( 178 PolicyBinding( 179 # Copy over all fields except the target and primary key 180 **{ 181 k.name: getattr(binding, k.name) 182 for k in PolicyBinding._meta.concrete_fields 183 if k.name != "target" and not k.primary_key 184 }, 185 target=app, 186 ) 187 ) 188 PolicyBinding.objects.bulk_create(new_bindings) 189 190 LOGGER.info( 191 "DCR: registered new client", 192 client_id=provider.client_id, 193 client_name=provider.name, 194 registered_by=access_token.user.username, 195 ) 196 197 # --- RFC 7591 ยง3.2.1 response ------------------------------------- 198 response_data: dict[str, Any] = { 199 "client_id": provider.client_id, 200 "client_id_issued_at": int(time.time()), 201 "redirect_uris": raw_uris, 202 "grant_types": grant_types, 203 "token_endpoint_auth_method": ( 204 auth_method if auth_method in AUTH_METHOD_TO_CLIENT_TYPE else "client_secret_basic" 205 ), 206 } 207 208 if client_type == ClientType.CONFIDENTIAL: 209 response_data["client_secret"] = provider.client_secret 210 response_data["client_secret_expires_at"] = 0 211 212 if client_name: 213 response_data["client_name"] = client_name 214 215 return JsonResponse(response_data, status=201) 216 217 def dispatch( 218 self, request: HttpRequest, application_slug: str, *args: Any, **kwargs: Any 219 ) -> HttpResponse: 220 self.application = get_object_or_404(Application, slug=application_slug) 221 self.provider = get_object_or_404(OAuth2Provider, pk=self.application.provider_id) 222 223 try: 224 self.dcr = OAuth2DynamicClientRegistration.objects.get(provider=self.provider) 225 except OAuth2DynamicClientRegistration.DoesNotExist: 226 return JsonResponse( 227 { 228 "error": "not_found", 229 "error_description": ( 230 "Dynamic client registration is not enabled for this provider." 231 ), 232 }, 233 status=404, 234 ) 235 236 return super().dispatch(request, application_slug, *args, **kwargs)
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
AUTH_METHOD_TO_CLIENT_TYPE =
{'client_secret_basic': ClientType.CONFIDENTIAL, 'client_secret_post': ClientType.CONFIDENTIAL, 'none': ClientType.PUBLIC}
@method_decorator(csrf_exempt, name='dispatch')
class
DynamicClientRegistrationView48@method_decorator(csrf_exempt, name="dispatch") 49class DynamicClientRegistrationView(View): 50 """RFC 7591 Dynamic Client Registration endpoint.""" 51 52 dcr: OAuth2DynamicClientRegistration 53 application: Application 54 provider: OAuth2Provider 55 56 def _authenticate_access_token(self, request: HttpRequest) -> AccessToken | None: 57 """Authenticate the request via a Bearer `AccessToken` carrying the 58 `goauthentik.io/oidc/dcr` scope, mirroring how `SCOPE_AUTHENTIK_API` 59 authenticates access to authentik's own API.""" 60 raw_token = validate_auth(request.headers.get("Authorization", "").encode()) 61 if not raw_token: 62 return None 63 access_token = AccessToken.objects.filter( 64 token=raw_token, _scope__icontains=SCOPE_AUTHENTIK_DCR 65 ).first() 66 if not access_token or SCOPE_AUTHENTIK_DCR not in access_token.scope: 67 return None 68 return access_token 69 70 def _check_policy_access(self, request: HttpRequest, user: User) -> bool: 71 engine = PolicyEngine(self.application, user, request) 72 engine.empty_result = AppAccessWithoutBindings.get() 73 engine.use_cache = False 74 engine.mode = self.application.policy_engine_mode 75 engine.build() 76 return engine.result.passing 77 78 def _unique_app_slug(self, base: str) -> str: 79 slug = slugify(base)[:200] or "client" 80 candidate = slug 81 counter = 1 82 while Application.objects.filter(slug=candidate).exists(): 83 candidate = f"{slug}-{counter}" 84 counter += 1 85 return candidate 86 87 @transaction.atomic 88 def post(self, request: HttpRequest, application_slug: str) -> HttpResponse: 89 # --- Access control ----------------------------------------------- 90 access_token = self._authenticate_access_token(request) 91 if access_token is None: 92 return _dcr_error( 93 "invalid_token", 94 "A valid access token with the " 95 f"'{SCOPE_AUTHENTIK_DCR}' scope is required to register clients.", 96 status=401, 97 ) 98 99 if not self._check_policy_access(request, access_token.user): 100 LOGGER.info("DCR registration rejected by policy", slug=application_slug) 101 return _dcr_error( 102 "access_denied", "Policy check failed for client registration.", status=403 103 ) 104 105 # --- Parse request body ------------------------------------------ 106 try: 107 metadata: dict[str, Any] = json.loads(request.body) 108 except json.JSONDecodeError, UnicodeDecodeError: 109 return _dcr_error("invalid_client_metadata", "Request body must be valid JSON.") 110 111 if not isinstance(metadata, dict): 112 return _dcr_error("invalid_client_metadata", "Request body must be a JSON object.") 113 114 raw_uris = metadata.get("redirect_uris") 115 if not raw_uris or not isinstance(raw_uris, list): 116 return _dcr_error( 117 "invalid_redirect_uri", "redirect_uris is required and must be a non-empty list." 118 ) 119 if not all(isinstance(u, str) for u in raw_uris): 120 return _dcr_error("invalid_redirect_uri", "All redirect_uris must be strings.") 121 122 redirect_uris = [ 123 RedirectURI(matching_mode=RedirectURIMatchingMode.STRICT, url=uri) for uri in raw_uris 124 ] 125 126 # --- Resolve settings -------------------------------------------- 127 auth_method = metadata.get("token_endpoint_auth_method", "client_secret_basic") 128 client_type = AUTH_METHOD_TO_CLIENT_TYPE.get(auth_method, ClientType.CONFIDENTIAL) 129 130 requested_grants = metadata.get("grant_types", [GrantType.AUTHORIZATION_CODE]) 131 if not isinstance(requested_grants, list): 132 return _dcr_error("invalid_client_metadata", "grant_types must be an array.") 133 if self.dcr.allowed_grant_types: 134 requested_grants = [g for g in requested_grants if g in self.dcr.allowed_grant_types] 135 grant_types = [g for g in requested_grants if g in GrantType.values] or [ 136 GrantType.AUTHORIZATION_CODE 137 ] 138 139 client_name = metadata.get("client_name", "") 140 141 # --- Create OAuth2Provider --------------------------------------- 142 provider = OAuth2Provider( 143 name=client_name or generate_id(), 144 client_id=generate_id(), 145 client_secret=generate_client_secret(), 146 client_type=client_type, 147 grant_types=grant_types, 148 authorization_flow=self.dcr.override_authorization_flow 149 or self.provider.authorization_flow, 150 invalidation_flow=self.dcr.override_invalidation_flow 151 or self.provider.invalidation_flow, 152 access_token_validity=self.dcr.access_token_validity 153 or self.provider.access_token_validity, 154 refresh_token_validity=self.dcr.refresh_token_validity 155 or self.provider.refresh_token_validity, 156 ) 157 provider.redirect_uris = redirect_uris 158 provider.save() 159 160 if self.dcr.override_property_mappings.exists(): 161 provider.property_mappings.set(self.dcr.override_property_mappings.all()) 162 else: 163 provider.property_mappings.set(self.provider.property_mappings.all()) 164 165 app_slug = self._unique_app_slug(client_name or provider.client_id) 166 app = Application.objects.create( 167 name=client_name or provider.client_id, 168 slug=app_slug, 169 provider=provider, 170 group=self.dcr.default_application_group, 171 policy_engine_mode=self.dcr.policy_engine_mode, 172 ) 173 bindings = PolicyBinding.objects.filter(target=self.dcr) 174 if not bindings.exists(): 175 bindings = PolicyBinding.objects.filter(target=self.application) 176 new_bindings = [] 177 for binding in bindings: 178 new_bindings.append( 179 PolicyBinding( 180 # Copy over all fields except the target and primary key 181 **{ 182 k.name: getattr(binding, k.name) 183 for k in PolicyBinding._meta.concrete_fields 184 if k.name != "target" and not k.primary_key 185 }, 186 target=app, 187 ) 188 ) 189 PolicyBinding.objects.bulk_create(new_bindings) 190 191 LOGGER.info( 192 "DCR: registered new client", 193 client_id=provider.client_id, 194 client_name=provider.name, 195 registered_by=access_token.user.username, 196 ) 197 198 # --- RFC 7591 ยง3.2.1 response ------------------------------------- 199 response_data: dict[str, Any] = { 200 "client_id": provider.client_id, 201 "client_id_issued_at": int(time.time()), 202 "redirect_uris": raw_uris, 203 "grant_types": grant_types, 204 "token_endpoint_auth_method": ( 205 auth_method if auth_method in AUTH_METHOD_TO_CLIENT_TYPE else "client_secret_basic" 206 ), 207 } 208 209 if client_type == ClientType.CONFIDENTIAL: 210 response_data["client_secret"] = provider.client_secret 211 response_data["client_secret_expires_at"] = 0 212 213 if client_name: 214 response_data["client_name"] = client_name 215 216 return JsonResponse(response_data, status=201) 217 218 def dispatch( 219 self, request: HttpRequest, application_slug: str, *args: Any, **kwargs: Any 220 ) -> HttpResponse: 221 self.application = get_object_or_404(Application, slug=application_slug) 222 self.provider = get_object_or_404(OAuth2Provider, pk=self.application.provider_id) 223 224 try: 225 self.dcr = OAuth2DynamicClientRegistration.objects.get(provider=self.provider) 226 except OAuth2DynamicClientRegistration.DoesNotExist: 227 return JsonResponse( 228 { 229 "error": "not_found", 230 "error_description": ( 231 "Dynamic client registration is not enabled for this provider." 232 ), 233 }, 234 status=404, 235 ) 236 237 return super().dispatch(request, application_slug, *args, **kwargs)
RFC 7591 Dynamic Client Registration endpoint.
application: authentik.core.models.Application
@transaction.atomic
def
post( self, request: django.http.request.HttpRequest, application_slug: str) -> django.http.response.HttpResponse:
87 @transaction.atomic 88 def post(self, request: HttpRequest, application_slug: str) -> HttpResponse: 89 # --- Access control ----------------------------------------------- 90 access_token = self._authenticate_access_token(request) 91 if access_token is None: 92 return _dcr_error( 93 "invalid_token", 94 "A valid access token with the " 95 f"'{SCOPE_AUTHENTIK_DCR}' scope is required to register clients.", 96 status=401, 97 ) 98 99 if not self._check_policy_access(request, access_token.user): 100 LOGGER.info("DCR registration rejected by policy", slug=application_slug) 101 return _dcr_error( 102 "access_denied", "Policy check failed for client registration.", status=403 103 ) 104 105 # --- Parse request body ------------------------------------------ 106 try: 107 metadata: dict[str, Any] = json.loads(request.body) 108 except json.JSONDecodeError, UnicodeDecodeError: 109 return _dcr_error("invalid_client_metadata", "Request body must be valid JSON.") 110 111 if not isinstance(metadata, dict): 112 return _dcr_error("invalid_client_metadata", "Request body must be a JSON object.") 113 114 raw_uris = metadata.get("redirect_uris") 115 if not raw_uris or not isinstance(raw_uris, list): 116 return _dcr_error( 117 "invalid_redirect_uri", "redirect_uris is required and must be a non-empty list." 118 ) 119 if not all(isinstance(u, str) for u in raw_uris): 120 return _dcr_error("invalid_redirect_uri", "All redirect_uris must be strings.") 121 122 redirect_uris = [ 123 RedirectURI(matching_mode=RedirectURIMatchingMode.STRICT, url=uri) for uri in raw_uris 124 ] 125 126 # --- Resolve settings -------------------------------------------- 127 auth_method = metadata.get("token_endpoint_auth_method", "client_secret_basic") 128 client_type = AUTH_METHOD_TO_CLIENT_TYPE.get(auth_method, ClientType.CONFIDENTIAL) 129 130 requested_grants = metadata.get("grant_types", [GrantType.AUTHORIZATION_CODE]) 131 if not isinstance(requested_grants, list): 132 return _dcr_error("invalid_client_metadata", "grant_types must be an array.") 133 if self.dcr.allowed_grant_types: 134 requested_grants = [g for g in requested_grants if g in self.dcr.allowed_grant_types] 135 grant_types = [g for g in requested_grants if g in GrantType.values] or [ 136 GrantType.AUTHORIZATION_CODE 137 ] 138 139 client_name = metadata.get("client_name", "") 140 141 # --- Create OAuth2Provider --------------------------------------- 142 provider = OAuth2Provider( 143 name=client_name or generate_id(), 144 client_id=generate_id(), 145 client_secret=generate_client_secret(), 146 client_type=client_type, 147 grant_types=grant_types, 148 authorization_flow=self.dcr.override_authorization_flow 149 or self.provider.authorization_flow, 150 invalidation_flow=self.dcr.override_invalidation_flow 151 or self.provider.invalidation_flow, 152 access_token_validity=self.dcr.access_token_validity 153 or self.provider.access_token_validity, 154 refresh_token_validity=self.dcr.refresh_token_validity 155 or self.provider.refresh_token_validity, 156 ) 157 provider.redirect_uris = redirect_uris 158 provider.save() 159 160 if self.dcr.override_property_mappings.exists(): 161 provider.property_mappings.set(self.dcr.override_property_mappings.all()) 162 else: 163 provider.property_mappings.set(self.provider.property_mappings.all()) 164 165 app_slug = self._unique_app_slug(client_name or provider.client_id) 166 app = Application.objects.create( 167 name=client_name or provider.client_id, 168 slug=app_slug, 169 provider=provider, 170 group=self.dcr.default_application_group, 171 policy_engine_mode=self.dcr.policy_engine_mode, 172 ) 173 bindings = PolicyBinding.objects.filter(target=self.dcr) 174 if not bindings.exists(): 175 bindings = PolicyBinding.objects.filter(target=self.application) 176 new_bindings = [] 177 for binding in bindings: 178 new_bindings.append( 179 PolicyBinding( 180 # Copy over all fields except the target and primary key 181 **{ 182 k.name: getattr(binding, k.name) 183 for k in PolicyBinding._meta.concrete_fields 184 if k.name != "target" and not k.primary_key 185 }, 186 target=app, 187 ) 188 ) 189 PolicyBinding.objects.bulk_create(new_bindings) 190 191 LOGGER.info( 192 "DCR: registered new client", 193 client_id=provider.client_id, 194 client_name=provider.name, 195 registered_by=access_token.user.username, 196 ) 197 198 # --- RFC 7591 ยง3.2.1 response ------------------------------------- 199 response_data: dict[str, Any] = { 200 "client_id": provider.client_id, 201 "client_id_issued_at": int(time.time()), 202 "redirect_uris": raw_uris, 203 "grant_types": grant_types, 204 "token_endpoint_auth_method": ( 205 auth_method if auth_method in AUTH_METHOD_TO_CLIENT_TYPE else "client_secret_basic" 206 ), 207 } 208 209 if client_type == ClientType.CONFIDENTIAL: 210 response_data["client_secret"] = provider.client_secret 211 response_data["client_secret_expires_at"] = 0 212 213 if client_name: 214 response_data["client_name"] = client_name 215 216 return JsonResponse(response_data, status=201)
def
dispatch( self, request: django.http.request.HttpRequest, application_slug: str, *args: Any, **kwargs: Any) -> django.http.response.HttpResponse:
218 def dispatch( 219 self, request: HttpRequest, application_slug: str, *args: Any, **kwargs: Any 220 ) -> HttpResponse: 221 self.application = get_object_or_404(Application, slug=application_slug) 222 self.provider = get_object_or_404(OAuth2Provider, pk=self.application.provider_id) 223 224 try: 225 self.dcr = OAuth2DynamicClientRegistration.objects.get(provider=self.provider) 226 except OAuth2DynamicClientRegistration.DoesNotExist: 227 return JsonResponse( 228 { 229 "error": "not_found", 230 "error_description": ( 231 "Dynamic client registration is not enabled for this provider." 232 ), 233 }, 234 status=404, 235 ) 236 237 return super().dispatch(request, application_slug, *args, **kwargs)