SAML upstream logout doesn't happen - security issue
Describe the bug
We use Authentik as an Identity Broker: [some SAAS] ---oidc---> [Authentik] ---saml--->[Corporate IDP].
Logging in works fine. We have a problem with users (not) logging out.
What happens on logout:
- user logs out of SAAS
- SAAS triggers OIDC logout to Authentik
- Authentik invalidates the session in a simple flow: 10) "default-invalidation-logout" User Logout Stage terminates the session, then 20) Redirect Stage sends them to some page
- ⚠️ IDP keeps their session because nobody told them to logout ⚠️
Resulting security Issue:
- anybody using this browser will be able to log in to any app that uses IDP, because the IDP session is happily active until it times out hours later
What I expect to happen:
- user logs out of SAAS
- SAAS triggers OIDC logout to Authentik
- Authentik terminates the session and sends a SAML LogoutRequest to IDP
- IDP terminates the session and redirects to wherever it is configured to redirect on logout
What I tried:
- In SAML Source page, I added a SLO endpoint. I expected Authentik to send a properly formed LogoutRequest there. It didn't happen. The SLO endpoint is never triggered during a User Logout Stage.
- I dug through the code and noticed that if I visit a URL of https://my-authentik-server.com/source/saml/slug/slo/, I am redirected to the abovementioned SLO url from the "slug" SAML source. It is a simple redirect, no query string, no payload.
What I need:
- I need Authentik to send a properly formed LogoutRequest to upstream IDP when a user logs out of Authentik. Otherwise it creates a security risk where anybody can re-authenticate via that same source.
How to reproduce
- Create a SAML Source for an upstream IDP
- Log into Authentik using the SAML Source
- Log out of Authentik
- You will be logged out of Authentik but NOT the SAML Source.
- Try to log into Authentik again via the same source. You will log in immediately, because nobody terminated the upstream session.
Expected behavior
As above.
Screenshots
No response
Additional context
No response
Deployment Method
Docker
Version
2025.12.1
Relevant log output
Since my project cannot wait, I have built this functionality over the weekend. Here is the summary of the changes I made. This might give you an idea of how to implement thsi in the official version. Probably for the attention of @dewi-tik and @PeshekDotDev ? If you have any questions, I am happy to help.
SAML Source SLO (SP-Initiated) — Implementation Guideline
Authentik currently supports SLO for SAML Providers (authentik-as-IdP). This describes what's needed to add the missing SLO for SAML Sources (authentik-as-SP), and the non-obvious issues we encountered while implementing it.
1. Data Model Changes
- New fields on
SAMLSource:slo_binding(REDIRECT or POST — no POST_AUTO since the browser must visit the IdP) andsign_logout_request(boolean). - New model
SAMLSourceSession: tracks each login-via-SAML-source with the IdP'sSessionIndex,NameID, andNameIDFormat. Linked to both theUserand theAuthenticatedSessionvia FKs. Supports expiry viaExpiringModelusing the assertion'sSessionNotOnOrAfter.
2. Capturing Session Data at Login Time
ResponseProcessormust extractSessionIndex,NameID,NameIDFormat, andSessionNotOnOrAfterfrom the SAML assertion's<AuthnStatement>during response validation.- Data needs to be stored in two places: (a)
request.sessionand (b) on the processor instance. This dual-path is necessary becausedjango.contrib.auth.login()may flush/cycle the session, losing session-stored data. - A
user_logged_insignal handler picks up the session data and creates theSAMLSourceSessionrecord. TheAuthenticatedSessionmay not exist yet at signal time (ordering of signal handlers is not guaranteed), soget_or_createlogic is needed.
3. The LINK Action Path
- When a user is already authenticated and authenticates again via a SAML source, the
SourceFlowManagertakes the LINK action, not AUTH.user_logged_innever fires in this case. SAMLSourceFlowManager.handle_existing_link()must create theSAMLSourceSessiondirectly, bypassing the signal path entirely.
4. Reusing LogoutRequestProcessor
- The existing
LogoutRequestProcessoris tightly coupled toSAMLProvider. To reuse it for sources, introduce aSAMLLogoutConfigProtocol class so the processor works with any object providingsigning_kp,sign_logout_request,signature_algorithm, anddigest_algorithm. - Custom issuer:
SAMLSourcedoesn't have anissuerproperty the same way providers do. For a source acting as SP, the issuer is its SP metadata URL. Add anissuerparameter to the constructor to support this.
5. Hooking into the Logout Flow
- Reuse the existing
flow_pre_user_logoutsignal and the existingNativeLogoutStageView(the in-memory stage + frontend component that redirects/POSTs the user to the external IdP). - Critical: merge, don't overwrite. Both source and provider SLO handlers write to
PLAN_CONTEXT_SAML_LOGOUT_NATIVE_SESSIONS. The current code overwrites the context key. Both handlers must append to the existing list. Similarly, both must check ifNativeLogoutStageViewis already in the plan before injecting a duplicate.
6. Stage Insertion Index
- The current code inserts
NativeLogoutStageViewat a hardcodedindex=2. This breaks in two scenarios:- OIDC-triggered logout:
EndSessionViewappends aSessionEndStageto the plan. If the native logout stage lands afterSessionEndStage, the user gets redirected away before SLO executes. - Custom invalidation flows with stages after
UserLogoutStage(e.g., a redirect stage to a corporate homepage).
- OIDC-triggered logout:
- Fix: Insert
NativeLogoutStageViewatindex=1(right after the currentUserLogoutStageat index 0), so SLO always runs before any downstream stages.
7. SLO Callback View (SLOView)
- CSRF exemption required: The IdP POSTs a
LogoutResponsecross-origin, identical to how the ACS endpoint works. Must use@csrf_exempt. - Remove
LoginRequiredMixin: By the time the IdP redirects back,UserLogoutStagehas already calledlogout(). The user is anonymous. Requiring login would 302 to the login page. - Redirect back to the flow, not to the IdP: The current
SLOViewdoesredirect(source.slo_url)which would loop. Must redirect back to the flow executor so remaining stages can execute.
8. RelayState and the 80-Byte Limit
- SAML 2.0 Bindings spec (sections 3.4.3, 3.5.3) limits
RelayStateto 80 bytes for both Redirect and POST bindings. A full absolute URL does not fit. - Solution: Store the absolute flow return URL in the flow plan context (
PLAN_CONTEXT_SAML_RELAY_STATE). Send only the relative path (e.g.,/if/flow/default-invalidation-flow/) asRelayStateto the IdP. TheSLOViewresolves the return URL in priority order: (1) plan context from session, (2) RelayState from IdP response, (3) fallback to user interface. - Note:
stage_ok()persists the plan to the new (post-logout) session, so the plan context survives thelogout()call.
9. SP Metadata
- When
slo_urlis configured on the source, the SP metadata (/source/saml/<slug>/metadata/) should include a<SingleLogoutService>element advertising the SLO callback URL and binding. This allows IdPs consuming the metadata to auto-discover the SLO endpoint.
10. Frontend
- Add
SLO Bindingdropdown andSign Logout Requeststoggle to the SAML Source admin form.
11. Binding Value Casing (Non-Obvious)
- The source model stores binding values as uppercase (
"REDIRECT","POST"). However, the frontend's TypeScriptSAMLBindingsEnum(used byNativeLogoutStageView) expects lowercase ("redirect","post"). When building thelogout_datadict for the plan context, translate to the lowercase enum values.
Files Touched (for reference)
| File | Change Type |
|---|---|
sources/saml/models.py |
New model + fields |
sources/saml/migrations/0022_* |
Migration |
sources/saml/signals.py |
Two new signal handlers |
sources/saml/processors/response.py |
Session data extraction + FlowManager override |
sources/saml/processors/metadata.py |
SingleLogoutService in SP metadata |
sources/saml/views.py |
SLOView rewrite |
sources/saml/api/source.py |
Serializer + viewset fields |
providers/saml/processors/logout_request.py |
Generalize to work with sources (Protocol class) |
providers/saml/signals.py |
Fix merge bug + dedup stage injection |
stages/user_logout/stage.py |
No functional change (logging only) |
web/src/admin/sources/saml/SAMLSourceForm.ts |
UI fields |
Hey @headlesssetup, thank you for the pointers. I'll check some of the things you pointed out against my implementation. I wrote one last week, but I need some time to sync with other team members on minor implementation details. It will definitely be out by next release, but will probably take a week or two or review before it gets merged
That was quick, already next release, wow. Thank you so much @PeshekDotDev !
Out of curiosity, I asked Claude 4.6 to compare two implementations and highlight anything that might be useful for your PR. Here they are below. My semi-professional opinion is that no. 10 is important as the upgrade will break the existing SAML sources.
Suggestions for PR #20323 / SAML Source SLO
1. Add session expiry support to SAMLSourceSession
The PR's SAMLSourceSession is a plain models.Model with no expiry mechanism. SAML IdPs can include SessionNotOnOrAfter in the AuthnStatement, which defines when the session should be considered expired. Without honoring this, stale SAMLSourceSession records accumulate and could trigger logout requests for sessions the IdP has already expired. Consider inheriting from ExpiringModel (or at least adding a session_not_on_or_after field) and parsing the attribute from the SAML response during session creation.
2. Handle the LINK action path for session creation
The SAMLPostSourceStage approach creates SAMLSourceSession after a successful authentication flow. However, when a user is already authenticated and authenticates again via a SAML source, the SourceFlowManager takes the LINK action instead of AUTH. In this case, the full authentication flow may not run, and the post-source stage might not fire. This means SLO won't work for linked sessions. Consider explicitly handling this in SAMLSourceFlowManager or ensuring the stage runs for all action types.
3. LogoutResponseParser.verify_status() returns True on missing status elements
In authentik/common/saml/parsers/logout_response.py, verify_status() returns True (success) when <Status> or <StatusCode> elements are missing. Per the SAML spec (section 3.2.2), <Status> is a required element in <LogoutResponse>. Treating its absence as success is overly permissive. Consider returning False or raising an exception when <Status> is absent, as it likely indicates a malformed response.
4. _handle_logout_request doesn't verify signatures on incoming LogoutRequests
In SLOView._handle_logout_request(), the incoming LogoutRequest from the IdP is parsed but never signature-verified, even when the source has a verification_kp configured. A malicious actor could forge a LogoutRequest to log users out. The LogoutRequestParser should support optional signature verification using the IdP's certificate (similar to how ResponseProcessor verifies assertion/response signatures).
5. _handle_logout_request filters sessions by request.user, which may be anonymous
In SLOView._handle_logout_request():
SAMLSourceSession.objects.filter(
source=source,
user=request.user,
).delete()
If the IdP sends a LogoutRequest via a back-channel or after the user's session cookie has expired, request.user would be AnonymousUser, and this filter would match nothing. The LogoutRequest contains a NameID and SessionIndex -- consider looking up the SAMLSourceSession by those fields instead, which is how the SAML spec intends session resolution to work.
6. POST-binding LogoutResponse falls back to redirect when there's no flow
In SLOView._send_logout_response():
def _send_logout_response(self, response_builder, relay_state=None):
return redirect(response_builder.get_redirect_url(relay_state))
Even when the source's slo_binding is POST, this fallback always uses a redirect. If the IdP only supports POST-binding LogoutResponse, this would fail. Consider rendering a minimal auto-submit form directly (without needing a flow) as the fallback.
7. Flow plan manipulation in _handle_logout_response is fragile
In SLOView._handle_logout_response():
if relay_state and SESSION_KEY_PLAN in request.session:
plan: FlowPlan = request.session[SESSION_KEY_PLAN]
if plan.bindings:
plan.pop()
request.session[SESSION_KEY_PLAN] = plan
return redirect(relay_state)
This blindly pops the current stage from the plan assuming it's the RedirectStage that sent the user to the IdP. If anything else modifies the plan between the redirect and the callback, the wrong stage gets popped. Consider verifying the stage type before popping, or using a stage-specific marker/token to ensure the correct stage is advanced.
8. LogoutRequestParser should be made truly shared
The PR moves LogoutRequestParser to authentik/common/saml/parsers/ but it still imports decode_base64_and_inflate from authentik.providers.saml.utils.encoding. If the goal is a shared common module, the encoding utilities should also be moved to authentik/common/saml/ to avoid the source module depending on the provider module. The same applies to LogoutResponseParser and LogoutResponseBuilder, which both import from authentik.providers.saml.utils.
9. Metadata should include ResponseLocation for flexibility
The PR advertises both REDIRECT and POST bindings for SingleLogoutService, both pointing to the same Location. The SAML metadata spec allows an optional ResponseLocation attribute (for receiving LogoutResponse at a different URL than LogoutRequest). While not strictly required, documenting the assumption that both requests and responses arrive at the same endpoint would help administrators troubleshooting interop issues.
10. Consider adding a sign_authn_request migration for existing sources
The PR adds sign_authn_request with default=False, which changes the existing behavior. Previously, AuthnRequests were signed whenever a signing_kp was set. After the migration, existing sources with a signing keypair will stop signing AuthnRequests unless an admin manually enables the new flag. This is a silent behavioral regression that could break SSO for existing deployments. Consider defaulting sign_authn_request to True in the migration (or setting it based on whether signing_kp is non-null) to preserve backward compatibility.
11. SP-initiated SLO via _initiate_logout doesn't associate with a specific source
SLOView._initiate_logout() delegates to the brand's invalidation flow, which then triggers the flow_pre_user_logout signal. But the signal handler iterates over all SAMLSourceSession records for the user. If the user navigated to /source/saml/<specific-source>/slo/, the intent was likely to log out of that specific source only. Consider passing the source context through the flow plan so the signal handler can filter to just the intended source.
12. Clean up SAMLSourceSession records on session expiry / cleanup
There's no periodic task or signal to clean up SAMLSourceSession records when the underlying AuthenticatedSession expires or is deleted. While the CASCADE on the foreign key handles DB-level cleanup when the AuthenticatedSession row is deleted, Django session expiry doesn't always trigger row deletion immediately. Consider adding a periodic cleanup task or hooking into the session cleanup mechanism.
@dewi-tik you mentioned this would come in one of this years updates, and I do see a lot of SAML work (some of my customizations are now official, e.g. ForceAuthn). However, this is still not done - any timeframe? Thank you very much!
No strict timeframe at the moment but the linked PR (https://github.com/goauthentik/authentik/pull/20323) will address this.