Repository: goauthentik/authentik

Issue:
SAML source provider login is not working with Authentik version: 2024.4.x 
**Describe the bug**
We are testing Authentik version 2024.4.2 with our aws SAML application as source provider for Authentik but end up getting 405 error. The exact same setup works without any issue with earlier Authentik ver. 2024.2.3 


**To Reproduce**
Steps to reproduce the behavior:

1. Upgrade or initialise Authentik with version 2024.4.x
2. Setup SAML Source provider using step by step documentation provided here https://docs.goauthentik.io/docs/sources/saml/ 
3. #### SAML setting
     - User matching mode: Link users on unique identifier
     - SSO URL: https://portal.sso.eu-central-1.amazonaws.com/saml/assertion/XXXXXXXXX
     - Binding Type: Redirect binding     ( _changing Binding Type to other options don't fix it._ )
     - NameID Policy: Persistent
     - Pre-authentication flow: default-source-pre-authentication (Pre-Authentication)
     - Authentication flow: default-source-authentication (Welcome to authentik!)
     - Enrollment flow: default-source-enrollment (Welcome to authentik! Please select a username.)

**Expected behavior**
Authorise user to login via SAML source.

**Saml tracer logs**
```
POST https://authentik.bf-authentik-sandbox.aws.xyz.io/source/saml/bfsso/acs/ HTTP/1.1
sec-ch-ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
Origin: https://xyz.awsapps.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: cross-site
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://xyz.awsapps.com/
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8,de;q=0.7
Cookie: authentik_session=XXXXXXXXXX
HTTP/1.1 405
date: Mon, 13 May 2024 12:51:17 GMT
content-type: text/html; charset=utf-8
content-length: 23
allow: GET, HEAD, OPTIONS
content-encoding: gzip
referrer-policy: same-origin
vary: Accept-Encoding
vary: Cookie
x-authentik-id: b664cf3d40394b468f23535a96d82332
x-content-type-options: nosniff
x-frame-options: DENY
x-powered-by: authentik

```
**Logs**
Time | Container Logs
-- | -- 
13 May 2024 at 14:35 (UTC+2:00) | {"auth_via": "unauthenticated", "domain_url": "authentik.bf-authentik-sandbox.aws.xyz.io", "event": "/source/saml/bfsso/acs/", "host": "authentik.bf-authentik-sandbox.aws.xyz.io", "level": "info", "logger": "authentik.asgi", "method": "POST", "pid": 86, "remote": "0.0.0.0.", "request_id": "4f4c009723754141bc412e703fc715a2", "runtime": 111, "schema_name": "public", "scheme": "https", "status": 405, "timestamp": "2024-05-13T12:35:50.479708", "user": "", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"}
13 May 2024 at 14:35 (UTC+2:00) | {"auth_via": "unauthenticated", "domain_url": "authentik.bf-authentik-sandbox.aws.xyz.io", "event": "Task published", "host": "authentik.bf-authentik-sandbox.aws.xyz.io", "level": "info", "logger": "authentik.root.celery", "pid": 86, "request_id": "4f4c009723754141bc412e703fc715a2", "schema_name": "public", "task_id": "f022bbcc7463438086129504b5d001a0", "task_name": "authentik.events.tasks.event_notification_handler", "timestamp": "2024-05-13T12:35:50.478238"}
13 May 2024 at 14:35 (UTC+2:00) | {"action": "system_exception", "auth_via": "unauthenticated", "client_ip": "0.0.0.10", "context": {"asn": {"as_org": "M-net Telekommunikations GmbH", "asn": 8767, "network": "82.135.0.0/17"}, "geo": {"city": "Augsburg", "continent": "EU", "country": "DE", "lat": 48.3781, "long": 10.8567}, "http_request": {"args": {}, "method": "POST", "path": "/source/saml/bfsso/acs/", "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"}, "message": "Traceback (most recent call last):\n File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 518, in thread_handler\n raise exc_info[1]\n File \"/ak-root/venv/lib/python3.12/site-packages/django/core/handlers/base.py\", line 253, in _get_response_async\n response = await wrapped_callback(\n ^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 468, in __call__\n ret = await asyncio.shield(exec_coro)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/current_thread_executor.py\", line 40, in run\n result = self.fn(*self.args, **self.kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/asgiref/sync.py\", line 522, in thread_handler\n return func(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django/views/generic/base.py\", line 104, in view\n return self.dispatch(request, *args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django/utils/decorators.py\", line 48, in _wrapper\n return bound_method(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django/views/decorators/csrf.py\", line 65, in _view_wrapper\n return view_func(request, *args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django/views/generic/base.py\", line 143, in dispatch\n return handler(request, *args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/authentik/sources/saml/views.py\", line 165, in post\n return processor.prepare_flow_manager().get_flow()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/authentik/core/sources/flow_manager.py\", line 180, in get_flow\n return self.handle_auth(connection)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/authentik/core/sources/flow_manager.py\", line 288, in handle_auth\n return self._prepare_flow(\n ^^^^^^^^^^^^^^^^^^^\n File \"/authentik/core/sources/flow_manager.py\", line 269, in _prepare_flow\n plan = planner.plan(self.request, kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/authentik/flows/planner.py\", line 206, in plan\n cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)\n File \"/ak-root/venv/lib/python3.12/site-packages/django_redis/cache.py\", line 29, in _decorator\n return method(self, *args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django_redis/cache.py\", line 81, in set\n return self.client.set(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django_redis/client/default.py\", line 143, in set\n nvalue = self.encode(value)\n ^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django_redis/client/default.py\", line 461, in encode\n value = self._serializer.dumps(value)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/ak-root/venv/lib/python3.12/site-packages/django_redis/serializers/pickle.py\", line 29, in dumps\n return pickle.dumps(value, self._pickle_version)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nbuiltins.TypeError: cannot pickle 'RestrictedElement' object"}, "domain_url": "authentik.bf-authentik-sandbox.aws.xyz.io", "event": "Created Event", "host": "authentik.bf-authentik-sandbox.aws.xyz.io", "level": "info", "logger": "authentik.events.models", "pid": 86, "request_id": "4f4c009723754141bc412e703fc715a2", "schema_name": "public", "timestamp": "2024-05-13T12:35:50.424355", "user": {"email": "", "is_anonymous": true, "pk": 1, "username": "AnonymousUser"}}


**Version and Deployment (please complete the following information):**

-   authentik version: 2024.4.x
-   Deployment: docker-compose

**Additional context**
This issue might be related to this comment here -> https://github.com/goauthentik/authentik/issues/4165#issuecomment-2097922867 


Discussion:

Resolving patch:
diff --git a/authentik/core/sources/flow_manager.py b/authentik/core/sources/flow_manager.py
--- a/authentik/core/sources/flow_manager.py
+++ b/authentik/core/sources/flow_manager.py
@@ -264,6 +264,7 @@ def _prepare_flow(
         planner = FlowPlanner(flow)
         # We append some stages so the initial flow we get might be empty
         planner.allow_empty_flows = True
+        planner.use_cache = False
         plan = planner.plan(self.request, kwargs)
         for stage in self.get_stages_to_append(flow):
             plan.append_stage(stage)
diff --git a/authentik/flows/planner.py b/authentik/flows/planner.py
--- a/authentik/flows/planner.py
+++ b/authentik/flows/planner.py
@@ -203,7 +203,8 @@ def plan(self, request: HttpRequest, default_context: dict[str, Any] | None = No
                 "f(plan): building plan",
             )
             plan = self._build_plan(user, request, default_context)
-            cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)
+            if self.use_cache:
+                cache.set(cache_key(self.flow, user), plan, CACHE_TIMEOUT)
             if not plan.bindings and not self.allow_empty_flows:
                 raise EmptyFlowException()
             return plan


Test patch: