authentik.providers.oauth2.views.end_session
oauth2 provider end_session Views
1"""oauth2 provider end_session Views""" 2 3from re import fullmatch 4from urllib.parse import quote, urlparse 5 6from django.http import Http404, HttpRequest, HttpResponse 7from django.shortcuts import get_object_or_404 8from jwt import PyJWTError 9from jwt import decode as jwt_decode 10 11from authentik.common.oauth.constants import ( 12 FORBIDDEN_URI_SCHEMES, 13 OAUTH2_BINDING, 14 PLAN_CONTEXT_OIDC_LOGOUT_IFRAME_SESSIONS, 15 PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI, 16) 17from authentik.core.models import Application, AuthenticatedSession 18from authentik.flows.models import Flow, in_memory_stage 19from authentik.flows.planner import ( 20 PLAN_CONTEXT_APPLICATION, 21 FlowPlanner, 22) 23from authentik.flows.stage import SessionEndStage 24from authentik.flows.views.executor import SESSION_KEY_PLAN 25from authentik.lib.views import bad_request_message 26from authentik.policies.views import PolicyAccessView 27from authentik.providers.iframe_logout import IframeLogoutStageView 28from authentik.providers.oauth2.errors import TokenError 29from authentik.providers.oauth2.models import ( 30 AccessToken, 31 JWTAlgorithms, 32 OAuth2LogoutMethod, 33 OAuth2Provider, 34 OAuth2SessionLogin, 35 RedirectURIMatchingMode, 36) 37from authentik.providers.oauth2.tasks import send_backchannel_logout_request 38from authentik.providers.oauth2.utils import build_frontchannel_logout_url 39 40 41def is_iframe_request(request: HttpRequest) -> bool: 42 """Treat requests without Fetch Metadata as possible iframe callbacks.""" 43 return request.headers.get("Sec-Fetch-Dest") in (None, "iframe", "frame") 44 45 46class EndSessionView(PolicyAccessView): 47 """OIDC RP-Initiated Logout endpoint""" 48 49 flow: Flow 50 post_logout_redirect_uri: str | None 51 52 def resolve_provider_application(self): 53 self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"]) 54 self.provider = self.application.get_provider() 55 if not self.provider: 56 raise Http404 57 self.flow = self.provider.invalidation_flow or self.request.brand.flow_invalidation 58 if not self.flow: 59 raise Http404 60 61 def handle_no_permission(self) -> HttpResponse: 62 """RP-Initiated Logout is idempotent: an unauthenticated request is a 63 valid no-op, so run the invalidation flow instead of redirecting to 64 the authentication flow.""" 65 return self.get(self.request, *self.args, **self.kwargs) 66 67 def validate(self): 68 # Parse end session parameters 69 query_dict = self.request.POST if self.request.method == "POST" else self.request.GET 70 state = query_dict.get("state") 71 request_redirect_uri = query_dict.get("post_logout_redirect_uri") 72 id_token_hint = query_dict.get("id_token_hint") 73 self.post_logout_redirect_uri = None 74 75 # OIDC Certification: Verify id_token_hint. If invalid or missing, throw an error 76 if id_token_hint: 77 # Load a fresh provider instance that's not part of the flow 78 # since it'll have the cryptography Certificate that can't be pickled 79 provider = OAuth2Provider.objects.get(pk=self.provider.pk) 80 key, alg = provider.jwt_key 81 if alg != JWTAlgorithms.HS256: 82 key = provider.signing_key.public_key 83 try: 84 jwt_decode( 85 id_token_hint, 86 key, 87 algorithms=[alg], 88 audience=provider.client_id, 89 issuer=provider.get_issuer(self.request), 90 # ID Tokens are short-lived; a logout request arriving 91 # after expiry is still legitimate and must succeed. 92 options={"verify_exp": False}, 93 ) 94 except PyJWTError: 95 raise TokenError("invalid_request").with_cause( 96 "id_token_hint_decode_failed" 97 ) from None 98 99 if request_redirect_uri and self.provider.post_logout_redirect_uris: 100 # OIDC Certification: id_token_hint required with post_logout_redirect_uri 101 if not id_token_hint: 102 raise TokenError("invalid_request").with_cause("id_token_hint_missing") 103 if urlparse(request_redirect_uri).scheme in FORBIDDEN_URI_SCHEMES: 104 raise TokenError("invalid_request").with_cause("post_logout_redirect_uri") 105 for allowed in self.provider.post_logout_redirect_uris: 106 if allowed.matching_mode == RedirectURIMatchingMode.STRICT: 107 if request_redirect_uri == allowed.url: 108 self.post_logout_redirect_uri = request_redirect_uri 109 break 110 elif allowed.matching_mode == RedirectURIMatchingMode.REGEX: 111 if fullmatch(allowed.url, request_redirect_uri): 112 self.post_logout_redirect_uri = request_redirect_uri 113 break 114 # OIDC Certification: OP MUST NOT perform post-logout redirection 115 # if the supplied URI does not exactly match a registered one 116 if self.post_logout_redirect_uri is None: 117 raise TokenError("invalid_request").with_cause("invalid_post_logout_redirect_uri") 118 119 # Append state to the redirect URI if both are present 120 if self.post_logout_redirect_uri and state: 121 separator = "&" if "?" in self.post_logout_redirect_uri else "?" 122 self.post_logout_redirect_uri = ( 123 f"{self.post_logout_redirect_uri}{separator}state={quote(state, safe='')}" 124 ) 125 126 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 127 """Preserve the running logout plan when a front-channel iframe calls back.""" 128 plan = request.session.get(SESSION_KEY_PLAN) 129 # A top-level navigation starts a new logout, even if an iframe stage was abandoned. 130 # Without Fetch Metadata, only the current iframe stage identifies a callback. 131 if ( 132 is_iframe_request(request) 133 and plan 134 and plan.bindings 135 and plan.bindings[0].stage.view == IframeLogoutStageView 136 ): 137 return HttpResponse(status=200) 138 return super().dispatch(request, *args, **kwargs) 139 140 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 141 """Dispatch the flow planner for the invalidation flow""" 142 try: 143 self.validate() 144 except TokenError as exc: 145 return bad_request_message( 146 self.request, 147 exc.description, 148 ) 149 planner = FlowPlanner(self.flow) 150 planner.allow_empty_flows = True 151 152 context = { 153 PLAN_CONTEXT_APPLICATION: self.application, 154 } 155 156 if self.post_logout_redirect_uri: 157 context[PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI] = self.post_logout_redirect_uri 158 159 frontchannel_logout_url = None 160 161 # An unauthenticated logout request (e.g. the session already expired) is a no-op: 162 # there is no session to end and no tokens to revoke. We still run the invalidation 163 # flow below, so that e.g. redirect stages are executed. 164 if request.user.is_authenticated: 165 auth_session = AuthenticatedSession.from_request(request, request.user) 166 167 session_key = ( 168 auth_session.session.session_key if auth_session and auth_session.session else None 169 ) 170 171 if self.provider.logout_method == OAuth2LogoutMethod.FRONTCHANNEL: 172 frontchannel_logout_url = build_frontchannel_logout_url( 173 self.provider, request, session_key 174 ) 175 176 login = OAuth2SessionLogin.objects.filter( 177 session=auth_session, 178 provider=self.provider, 179 ).first() 180 if ( 181 login 182 and self.provider.logout_method == OAuth2LogoutMethod.BACKCHANNEL 183 and self.provider.logout_uri 184 ): 185 send_backchannel_logout_request.send( 186 self.provider.pk, 187 login.iss, 188 login.sub, 189 session_key, 190 ) 191 if login: 192 # The RP is logged out of this session now. This also prevents a duplicate 193 # logout when UserLogoutStage triggers the logout and session deletion signals 194 login.delete() 195 196 if frontchannel_logout_url: 197 context[PLAN_CONTEXT_OIDC_LOGOUT_IFRAME_SESSIONS] = [ 198 { 199 "url": frontchannel_logout_url, 200 "provider_name": self.provider.name, 201 "binding": OAUTH2_BINDING, 202 "provider_type": ( 203 f"{self.provider._meta.app_label}.{self.provider._meta.model_name}" 204 ), 205 } 206 ] 207 208 access_tokens = AccessToken.objects.filter( 209 user=request.user, 210 provider=self.provider, 211 ) 212 if auth_session: 213 access_tokens = access_tokens.filter(session=auth_session) 214 access_tokens.delete() 215 216 plan = planner.plan(request, context) 217 218 if frontchannel_logout_url: 219 plan.insert_stage(in_memory_stage(IframeLogoutStageView)) 220 221 plan.append_stage(in_memory_stage(SessionEndStage)) 222 return plan.to_redirect(self.request, self.flow) 223 224 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 225 """Handle POST requests for logout (same as GET per OIDC spec)""" 226 return self.get(request, *args, **kwargs)
def
is_iframe_request(request: django.http.request.HttpRequest) -> bool:
42def is_iframe_request(request: HttpRequest) -> bool: 43 """Treat requests without Fetch Metadata as possible iframe callbacks.""" 44 return request.headers.get("Sec-Fetch-Dest") in (None, "iframe", "frame")
Treat requests without Fetch Metadata as possible iframe callbacks.
47class EndSessionView(PolicyAccessView): 48 """OIDC RP-Initiated Logout endpoint""" 49 50 flow: Flow 51 post_logout_redirect_uri: str | None 52 53 def resolve_provider_application(self): 54 self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"]) 55 self.provider = self.application.get_provider() 56 if not self.provider: 57 raise Http404 58 self.flow = self.provider.invalidation_flow or self.request.brand.flow_invalidation 59 if not self.flow: 60 raise Http404 61 62 def handle_no_permission(self) -> HttpResponse: 63 """RP-Initiated Logout is idempotent: an unauthenticated request is a 64 valid no-op, so run the invalidation flow instead of redirecting to 65 the authentication flow.""" 66 return self.get(self.request, *self.args, **self.kwargs) 67 68 def validate(self): 69 # Parse end session parameters 70 query_dict = self.request.POST if self.request.method == "POST" else self.request.GET 71 state = query_dict.get("state") 72 request_redirect_uri = query_dict.get("post_logout_redirect_uri") 73 id_token_hint = query_dict.get("id_token_hint") 74 self.post_logout_redirect_uri = None 75 76 # OIDC Certification: Verify id_token_hint. If invalid or missing, throw an error 77 if id_token_hint: 78 # Load a fresh provider instance that's not part of the flow 79 # since it'll have the cryptography Certificate that can't be pickled 80 provider = OAuth2Provider.objects.get(pk=self.provider.pk) 81 key, alg = provider.jwt_key 82 if alg != JWTAlgorithms.HS256: 83 key = provider.signing_key.public_key 84 try: 85 jwt_decode( 86 id_token_hint, 87 key, 88 algorithms=[alg], 89 audience=provider.client_id, 90 issuer=provider.get_issuer(self.request), 91 # ID Tokens are short-lived; a logout request arriving 92 # after expiry is still legitimate and must succeed. 93 options={"verify_exp": False}, 94 ) 95 except PyJWTError: 96 raise TokenError("invalid_request").with_cause( 97 "id_token_hint_decode_failed" 98 ) from None 99 100 if request_redirect_uri and self.provider.post_logout_redirect_uris: 101 # OIDC Certification: id_token_hint required with post_logout_redirect_uri 102 if not id_token_hint: 103 raise TokenError("invalid_request").with_cause("id_token_hint_missing") 104 if urlparse(request_redirect_uri).scheme in FORBIDDEN_URI_SCHEMES: 105 raise TokenError("invalid_request").with_cause("post_logout_redirect_uri") 106 for allowed in self.provider.post_logout_redirect_uris: 107 if allowed.matching_mode == RedirectURIMatchingMode.STRICT: 108 if request_redirect_uri == allowed.url: 109 self.post_logout_redirect_uri = request_redirect_uri 110 break 111 elif allowed.matching_mode == RedirectURIMatchingMode.REGEX: 112 if fullmatch(allowed.url, request_redirect_uri): 113 self.post_logout_redirect_uri = request_redirect_uri 114 break 115 # OIDC Certification: OP MUST NOT perform post-logout redirection 116 # if the supplied URI does not exactly match a registered one 117 if self.post_logout_redirect_uri is None: 118 raise TokenError("invalid_request").with_cause("invalid_post_logout_redirect_uri") 119 120 # Append state to the redirect URI if both are present 121 if self.post_logout_redirect_uri and state: 122 separator = "&" if "?" in self.post_logout_redirect_uri else "?" 123 self.post_logout_redirect_uri = ( 124 f"{self.post_logout_redirect_uri}{separator}state={quote(state, safe='')}" 125 ) 126 127 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 128 """Preserve the running logout plan when a front-channel iframe calls back.""" 129 plan = request.session.get(SESSION_KEY_PLAN) 130 # A top-level navigation starts a new logout, even if an iframe stage was abandoned. 131 # Without Fetch Metadata, only the current iframe stage identifies a callback. 132 if ( 133 is_iframe_request(request) 134 and plan 135 and plan.bindings 136 and plan.bindings[0].stage.view == IframeLogoutStageView 137 ): 138 return HttpResponse(status=200) 139 return super().dispatch(request, *args, **kwargs) 140 141 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 142 """Dispatch the flow planner for the invalidation flow""" 143 try: 144 self.validate() 145 except TokenError as exc: 146 return bad_request_message( 147 self.request, 148 exc.description, 149 ) 150 planner = FlowPlanner(self.flow) 151 planner.allow_empty_flows = True 152 153 context = { 154 PLAN_CONTEXT_APPLICATION: self.application, 155 } 156 157 if self.post_logout_redirect_uri: 158 context[PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI] = self.post_logout_redirect_uri 159 160 frontchannel_logout_url = None 161 162 # An unauthenticated logout request (e.g. the session already expired) is a no-op: 163 # there is no session to end and no tokens to revoke. We still run the invalidation 164 # flow below, so that e.g. redirect stages are executed. 165 if request.user.is_authenticated: 166 auth_session = AuthenticatedSession.from_request(request, request.user) 167 168 session_key = ( 169 auth_session.session.session_key if auth_session and auth_session.session else None 170 ) 171 172 if self.provider.logout_method == OAuth2LogoutMethod.FRONTCHANNEL: 173 frontchannel_logout_url = build_frontchannel_logout_url( 174 self.provider, request, session_key 175 ) 176 177 login = OAuth2SessionLogin.objects.filter( 178 session=auth_session, 179 provider=self.provider, 180 ).first() 181 if ( 182 login 183 and self.provider.logout_method == OAuth2LogoutMethod.BACKCHANNEL 184 and self.provider.logout_uri 185 ): 186 send_backchannel_logout_request.send( 187 self.provider.pk, 188 login.iss, 189 login.sub, 190 session_key, 191 ) 192 if login: 193 # The RP is logged out of this session now. This also prevents a duplicate 194 # logout when UserLogoutStage triggers the logout and session deletion signals 195 login.delete() 196 197 if frontchannel_logout_url: 198 context[PLAN_CONTEXT_OIDC_LOGOUT_IFRAME_SESSIONS] = [ 199 { 200 "url": frontchannel_logout_url, 201 "provider_name": self.provider.name, 202 "binding": OAUTH2_BINDING, 203 "provider_type": ( 204 f"{self.provider._meta.app_label}.{self.provider._meta.model_name}" 205 ), 206 } 207 ] 208 209 access_tokens = AccessToken.objects.filter( 210 user=request.user, 211 provider=self.provider, 212 ) 213 if auth_session: 214 access_tokens = access_tokens.filter(session=auth_session) 215 access_tokens.delete() 216 217 plan = planner.plan(request, context) 218 219 if frontchannel_logout_url: 220 plan.insert_stage(in_memory_stage(IframeLogoutStageView)) 221 222 plan.append_stage(in_memory_stage(SessionEndStage)) 223 return plan.to_redirect(self.request, self.flow) 224 225 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 226 """Handle POST requests for logout (same as GET per OIDC spec)""" 227 return self.get(request, *args, **kwargs)
OIDC RP-Initiated Logout endpoint
def
resolve_provider_application(self):
53 def resolve_provider_application(self): 54 self.application = get_object_or_404(Application, slug=self.kwargs["application_slug"]) 55 self.provider = self.application.get_provider() 56 if not self.provider: 57 raise Http404 58 self.flow = self.provider.invalidation_flow or self.request.brand.flow_invalidation 59 if not self.flow: 60 raise Http404
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
def
handle_no_permission(self) -> django.http.response.HttpResponse:
62 def handle_no_permission(self) -> HttpResponse: 63 """RP-Initiated Logout is idempotent: an unauthenticated request is a 64 valid no-op, so run the invalidation flow instead of redirecting to 65 the authentication flow.""" 66 return self.get(self.request, *self.args, **self.kwargs)
RP-Initiated Logout is idempotent: an unauthenticated request is a valid no-op, so run the invalidation flow instead of redirecting to the authentication flow.
def
validate(self):
68 def validate(self): 69 # Parse end session parameters 70 query_dict = self.request.POST if self.request.method == "POST" else self.request.GET 71 state = query_dict.get("state") 72 request_redirect_uri = query_dict.get("post_logout_redirect_uri") 73 id_token_hint = query_dict.get("id_token_hint") 74 self.post_logout_redirect_uri = None 75 76 # OIDC Certification: Verify id_token_hint. If invalid or missing, throw an error 77 if id_token_hint: 78 # Load a fresh provider instance that's not part of the flow 79 # since it'll have the cryptography Certificate that can't be pickled 80 provider = OAuth2Provider.objects.get(pk=self.provider.pk) 81 key, alg = provider.jwt_key 82 if alg != JWTAlgorithms.HS256: 83 key = provider.signing_key.public_key 84 try: 85 jwt_decode( 86 id_token_hint, 87 key, 88 algorithms=[alg], 89 audience=provider.client_id, 90 issuer=provider.get_issuer(self.request), 91 # ID Tokens are short-lived; a logout request arriving 92 # after expiry is still legitimate and must succeed. 93 options={"verify_exp": False}, 94 ) 95 except PyJWTError: 96 raise TokenError("invalid_request").with_cause( 97 "id_token_hint_decode_failed" 98 ) from None 99 100 if request_redirect_uri and self.provider.post_logout_redirect_uris: 101 # OIDC Certification: id_token_hint required with post_logout_redirect_uri 102 if not id_token_hint: 103 raise TokenError("invalid_request").with_cause("id_token_hint_missing") 104 if urlparse(request_redirect_uri).scheme in FORBIDDEN_URI_SCHEMES: 105 raise TokenError("invalid_request").with_cause("post_logout_redirect_uri") 106 for allowed in self.provider.post_logout_redirect_uris: 107 if allowed.matching_mode == RedirectURIMatchingMode.STRICT: 108 if request_redirect_uri == allowed.url: 109 self.post_logout_redirect_uri = request_redirect_uri 110 break 111 elif allowed.matching_mode == RedirectURIMatchingMode.REGEX: 112 if fullmatch(allowed.url, request_redirect_uri): 113 self.post_logout_redirect_uri = request_redirect_uri 114 break 115 # OIDC Certification: OP MUST NOT perform post-logout redirection 116 # if the supplied URI does not exactly match a registered one 117 if self.post_logout_redirect_uri is None: 118 raise TokenError("invalid_request").with_cause("invalid_post_logout_redirect_uri") 119 120 # Append state to the redirect URI if both are present 121 if self.post_logout_redirect_uri and state: 122 separator = "&" if "?" in self.post_logout_redirect_uri else "?" 123 self.post_logout_redirect_uri = ( 124 f"{self.post_logout_redirect_uri}{separator}state={quote(state, safe='')}" 125 )
def
dispatch( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
127 def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 128 """Preserve the running logout plan when a front-channel iframe calls back.""" 129 plan = request.session.get(SESSION_KEY_PLAN) 130 # A top-level navigation starts a new logout, even if an iframe stage was abandoned. 131 # Without Fetch Metadata, only the current iframe stage identifies a callback. 132 if ( 133 is_iframe_request(request) 134 and plan 135 and plan.bindings 136 and plan.bindings[0].stage.view == IframeLogoutStageView 137 ): 138 return HttpResponse(status=200) 139 return super().dispatch(request, *args, **kwargs)
Preserve the running logout plan when a front-channel iframe calls back.
def
get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
141 def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 142 """Dispatch the flow planner for the invalidation flow""" 143 try: 144 self.validate() 145 except TokenError as exc: 146 return bad_request_message( 147 self.request, 148 exc.description, 149 ) 150 planner = FlowPlanner(self.flow) 151 planner.allow_empty_flows = True 152 153 context = { 154 PLAN_CONTEXT_APPLICATION: self.application, 155 } 156 157 if self.post_logout_redirect_uri: 158 context[PLAN_CONTEXT_POST_LOGOUT_REDIRECT_URI] = self.post_logout_redirect_uri 159 160 frontchannel_logout_url = None 161 162 # An unauthenticated logout request (e.g. the session already expired) is a no-op: 163 # there is no session to end and no tokens to revoke. We still run the invalidation 164 # flow below, so that e.g. redirect stages are executed. 165 if request.user.is_authenticated: 166 auth_session = AuthenticatedSession.from_request(request, request.user) 167 168 session_key = ( 169 auth_session.session.session_key if auth_session and auth_session.session else None 170 ) 171 172 if self.provider.logout_method == OAuth2LogoutMethod.FRONTCHANNEL: 173 frontchannel_logout_url = build_frontchannel_logout_url( 174 self.provider, request, session_key 175 ) 176 177 login = OAuth2SessionLogin.objects.filter( 178 session=auth_session, 179 provider=self.provider, 180 ).first() 181 if ( 182 login 183 and self.provider.logout_method == OAuth2LogoutMethod.BACKCHANNEL 184 and self.provider.logout_uri 185 ): 186 send_backchannel_logout_request.send( 187 self.provider.pk, 188 login.iss, 189 login.sub, 190 session_key, 191 ) 192 if login: 193 # The RP is logged out of this session now. This also prevents a duplicate 194 # logout when UserLogoutStage triggers the logout and session deletion signals 195 login.delete() 196 197 if frontchannel_logout_url: 198 context[PLAN_CONTEXT_OIDC_LOGOUT_IFRAME_SESSIONS] = [ 199 { 200 "url": frontchannel_logout_url, 201 "provider_name": self.provider.name, 202 "binding": OAUTH2_BINDING, 203 "provider_type": ( 204 f"{self.provider._meta.app_label}.{self.provider._meta.model_name}" 205 ), 206 } 207 ] 208 209 access_tokens = AccessToken.objects.filter( 210 user=request.user, 211 provider=self.provider, 212 ) 213 if auth_session: 214 access_tokens = access_tokens.filter(session=auth_session) 215 access_tokens.delete() 216 217 plan = planner.plan(request, context) 218 219 if frontchannel_logout_url: 220 plan.insert_stage(in_memory_stage(IframeLogoutStageView)) 221 222 plan.append_stage(in_memory_stage(SessionEndStage)) 223 return plan.to_redirect(self.request, self.flow)
Dispatch the flow planner for the invalidation flow
def
post( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
225 def post(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: 226 """Handle POST requests for logout (same as GET per OIDC spec)""" 227 return self.get(request, *args, **kwargs)
Handle POST requests for logout (same as GET per OIDC spec)