You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "stephen-bracken (via GitHub)" <gi...@apache.org> on 2026/07/30 22:33:02 UTC

[PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

stephen-bracken opened a new pull request, #70800:
URL: https://github.com/apache/airflow/pull/70800

    <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull request.
   Write a good git commit message following this guide: https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   related: #70550
   
   Add KeycloakJWTMiddleware to KeycloakAuthManager
   ---
   
   Add middleware to extract tokens from the request cookies and attach them to the user during auth requests.
   
   
   ##### Was generative AI tooling used to co-author this PR?
   
   <!--
   If generative AI tooling has been used in the process of authoring this PR, please
   change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by".
   -->
   
   - [ ] Yes (please specify the tool below)
   - [X] No
   
   <!--
   Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   -->
   
   ---
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "stephen-bracken (via GitHub)" <gi...@apache.org>.
stephen-bracken commented on PR #70800:
URL: https://github.com/apache/airflow/pull/70800#issuecomment-5147466763

   I thought I would make the new JWT management an opt-in feature initially, I can take out the config if you don't think its necessary


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "stephen-bracken (via GitHub)" <gi...@apache.org>.
stephen-bracken commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3696676052


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
+from jwt import ExpiredSignatureError, InvalidTokenError
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from airflow.api_fastapi.app import get_auth_manager
+from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
+from airflow.api_fastapi.core_api import security as core_api_security
+from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.constants import (
+    COOKIE_NAME_ACCESS_TOKEN,
+    COOKIE_NAME_REFRESH_TOKEN,
+)
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: ignore[no-redef]
+        """In case it is using a version of Airflow without ``AuthManagerRefreshTokenExpiredException``."""
+
+        pass
+
+
+if AIRFLOW_V_3_1_8_PLUS:
+    from airflow.api_fastapi.app import get_cookie_path
+else:
+    get_cookie_path = lambda: "/"
+
+if TYPE_CHECKING:
+    from fastapi import Request, Response
+
+    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import KeycloakAuthManager
+    from airflow.providers.keycloak.auth_manager.user import KeycloakAuthManagerUser
+
+
+class KeycloakJWTMiddleware(BaseHTTPMiddleware):
+    """
+    Attach the Keycloak JWT tokens to the user.
+
+    Gets the Keycloak JWT tokens from the request cookies
+    and attaches them to the user. If the token is expired,
+    attempt to refresh it using the refresh token.
+    """
+
+    async def dispatch(self, request: Request, call_next):
+        user = None
+        new_token = None
+        new_user = None
+        try:
+            try:
+                new_user, current_user = await self._refresh_user(request)
+                user = new_user or current_user
+            except (
+                AuthManagerRefreshTokenExpiredException,
+                ExpiredSignatureError,
+                InvalidTokenError,
+                HTTPException,
+            ):
+                new_token = ""
+
+            if user is not None:
+                request.state.user = user
+
+                user_injected = getattr(
+                    core_api_security,
+                    "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+                    None,
+                )
+                if user_injected is not None:
+                    request.state.user_authenticated_via = user_injected
+
+            response = await call_next(request)
+
+            if new_user or new_token is not None:
+                secure = request.base_url.scheme == "https" or bool(conf.get("api", "ssl_cert", fallback=""))
+                cookie_path = get_cookie_path()
+                if new_token == "":
+                    response.set_cookie(
+                        COOKIE_NAME_JWT_TOKEN,
+                        new_token,
+                        path=cookie_path,
+                        httponly=True,
+                        secure=secure,
+                        samesite="lax",
+                        max_age=0,
+                    )
+                    if cookie_path != "/":
+                        response.set_cookie(
+                            COOKIE_NAME_JWT_TOKEN,
+                            "",
+                            path="/",
+                            httponly=True,
+                            secure=secure,
+                            samesite="lax",
+                            max_age=0,
+                        )
+                else:
+                    response = await self._set_new_token(new_user, secure, response, cookie_path)
+
+        except HTTPException as exc:

Review Comment:
   The `HTTPException` except pattern is used in the original `JWTRefreshMiddleware` that this is based on:
   https://github.com/apache/airflow/blob/b2d1d8183dcea1813a92e2ef5a94aebac4c143e8/airflow-core/src/airflow/api_fastapi/auth/middlewares/refresh_token.py#L94
   
   The pattern could be wrong, but I am being consistent with the existing JWT middleware here



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "stephen-bracken (via GitHub)" <gi...@apache.org>.
stephen-bracken commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3696662157


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   Since we haven't released a version that uses the `access_token` and `refresh_token` cookies yet, I don't think this is necessary.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #70800:
URL: https://github.com/apache/airflow/pull/70800


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #70800:
URL: https://github.com/apache/airflow/pull/70800#issuecomment-5147067865

   Why do we need a config here?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #70800:
URL: https://github.com/apache/airflow/pull/70800#issuecomment-5147498993

   Yeah I think it would be better without config. That creates complexity


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3700185224


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   Update: keycloak is now included in the 2026-08-01 release wave (#70932), and the forced-logout note is written into the keycloak 0.9.0 changelog there — so this is documented without any change needed on this PR. Resolving.
   
   ---
   Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3696641142


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   Renaming these leaves credentials behind in the browser that logout no longer clears.
   
   `access_token` becomes `_access_token` and `refresh_token` becomes `_refresh_token`, while `COOKIE_NAME_USER_ID` and `COOKIE_NAME_NAME` are dropped entirely. Anyone with a live session is holding cookies under the old names, and after this change nothing writes or deletes them — `logout_callback` only deletes the new names now, and the `delete_cookie` calls for `user_id` and `name` are removed outright.
   
   A refresh token is a credential, so "log out" leaving one in the browser is the wrong behaviour even for a short window. They are session cookies, with no `max_age` or `expires`, so they do go when the browser closes — that bounds the exposure but does not fix logout.
   
   Keeping the legacy names deleted in `logout_callback` for one release would close it.
   
   Worth noting the upgrade behaviour too, since nothing currently mentions it: an existing session sends the old cookie names, `_refresh_user` reads the new ones, gets `None`, raises 401, and `dispatch` clears the Airflow JWT. Every logged-in user is signed out by the upgrade. That is handled gracefully rather than erroring, but it should be a deliberate, documented choice rather than a side effect.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
+from jwt import ExpiredSignatureError, InvalidTokenError
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from airflow.api_fastapi.app import get_auth_manager
+from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
+from airflow.api_fastapi.core_api import security as core_api_security
+from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.constants import (
+    COOKIE_NAME_ACCESS_TOKEN,
+    COOKIE_NAME_REFRESH_TOKEN,
+)
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: ignore[no-redef]
+        """In case it is using a version of Airflow without ``AuthManagerRefreshTokenExpiredException``."""
+
+        pass
+
+
+if AIRFLOW_V_3_1_8_PLUS:
+    from airflow.api_fastapi.app import get_cookie_path
+else:
+    get_cookie_path = lambda: "/"

Review Comment:
   Minor: a `def` reads better than a lambda bound to a name here, and it is what ruff's E731 asks for where enabled. Same pattern appears in `routes/login.py`.
   
   ```python
   def get_cookie_path() -> str:
       return "/"
   ```



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
+from jwt import ExpiredSignatureError, InvalidTokenError
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from airflow.api_fastapi.app import get_auth_manager
+from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
+from airflow.api_fastapi.core_api import security as core_api_security
+from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.constants import (
+    COOKIE_NAME_ACCESS_TOKEN,
+    COOKIE_NAME_REFRESH_TOKEN,
+)
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: ignore[no-redef]
+        """In case it is using a version of Airflow without ``AuthManagerRefreshTokenExpiredException``."""
+
+        pass
+
+
+if AIRFLOW_V_3_1_8_PLUS:
+    from airflow.api_fastapi.app import get_cookie_path
+else:
+    get_cookie_path = lambda: "/"
+
+if TYPE_CHECKING:
+    from fastapi import Request, Response
+
+    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import KeycloakAuthManager
+    from airflow.providers.keycloak.auth_manager.user import KeycloakAuthManagerUser
+
+
+class KeycloakJWTMiddleware(BaseHTTPMiddleware):
+    """
+    Attach the Keycloak JWT tokens to the user.
+
+    Gets the Keycloak JWT tokens from the request cookies
+    and attaches them to the user. If the token is expired,
+    attempt to refresh it using the refresh token.
+    """
+
+    async def dispatch(self, request: Request, call_next):
+        user = None
+        new_token = None
+        new_user = None
+        try:
+            try:
+                new_user, current_user = await self._refresh_user(request)
+                user = new_user or current_user
+            except (
+                AuthManagerRefreshTokenExpiredException,
+                ExpiredSignatureError,
+                InvalidTokenError,
+                HTTPException,
+            ):
+                new_token = ""
+
+            if user is not None:
+                request.state.user = user
+
+                user_injected = getattr(
+                    core_api_security,
+                    "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+                    None,
+                )
+                if user_injected is not None:
+                    request.state.user_authenticated_via = user_injected
+
+            response = await call_next(request)
+
+            if new_user or new_token is not None:
+                secure = request.base_url.scheme == "https" or bool(conf.get("api", "ssl_cert", fallback=""))
+                cookie_path = get_cookie_path()
+                if new_token == "":
+                    response.set_cookie(
+                        COOKIE_NAME_JWT_TOKEN,
+                        new_token,
+                        path=cookie_path,
+                        httponly=True,
+                        secure=secure,
+                        samesite="lax",
+                        max_age=0,
+                    )
+                    if cookie_path != "/":
+                        response.set_cookie(
+                            COOKIE_NAME_JWT_TOKEN,
+                            "",
+                            path="/",
+                            httponly=True,
+                            secure=secure,
+                            samesite="lax",
+                            max_age=0,
+                        )
+                else:
+                    response = await self._set_new_token(new_user, secure, response, cookie_path)
+
+        except HTTPException as exc:

Review Comment:
   This `except` is scoped wider than the code it needs to protect — the `try` also wraps `await call_next(request)`.
   
   If an `HTTPException` escapes a downstream handler, this middleware converts it into its own `JSONResponse`, bypassing FastAPI's registered exception handlers and changing the error shape for responses that have nothing to do with authentication.
   
   I am not certain it is reachable: FastAPI's `ExceptionMiddleware` normally handles `HTTPException` inside `call_next`, so whether anything escapes depends on middleware ordering. So treat this as a question rather than a defect — but narrowing the `try` to just the refresh block removes the doubt entirely, and makes the intent obvious to the next reader.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3700146795


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   You're right, and I checked it properly: those names were never released.
   
   At `providers-keycloak/0.8.2` the provider's `constants.py` contains only the `CONF_*` entries — no cookie names at all. `login.py` defined just `COOKIE_NAME_ID_TOKEN = "_id_token"` and `COOKIE_NAME_OAUTH_STATE = "_oauth_state"` locally (both unchanged by this PR) and imported `COOKIE_NAME_JWT_TOKEN` from core; the Keycloak `access_token`/`refresh_token` lived in the Airflow JWT claims, not in cookies. All six `COOKIE_NAME_*` constants arrived with #70550, which is not an ancestor of the 0.8.2 tag.
   
   So there are no legacy cookies in anyone's browser and nothing for `logout_callback` to miss. Withdrawing that.
   
   The upgrade behaviour is the part I would still like written down. A 0.8.2 session carries the tokens in the JWT claims, so after upgrading `_refresh_user` finds no `_access_token`/`_refresh_token` cookie, returns 401, and `dispatch` clears the Airflow JWT — every logged-in user is signed out once. I agree that is the right call; it just deserves a line in the keycloak changelog for whichever release ships it, so operators are not surprised by a fleet-wide logout.
   
   ---
   Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -0,0 +1,243 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
+from jwt import ExpiredSignatureError, InvalidTokenError
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from airflow.api_fastapi.app import get_auth_manager
+from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
+from airflow.api_fastapi.core_api import security as core_api_security
+from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.constants import (
+    COOKIE_NAME_ACCESS_TOKEN,
+    COOKIE_NAME_REFRESH_TOKEN,
+)
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: ignore[no-redef]
+        """In case it is using a version of Airflow without ``AuthManagerRefreshTokenExpiredException``."""
+
+        pass
+
+
+if AIRFLOW_V_3_1_8_PLUS:
+    from airflow.api_fastapi.app import get_cookie_path
+else:
+    get_cookie_path = lambda: "/"
+
+if TYPE_CHECKING:
+    from fastapi import Request, Response
+
+    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import KeycloakAuthManager
+    from airflow.providers.keycloak.auth_manager.user import KeycloakAuthManagerUser
+
+
+class KeycloakJWTMiddleware(BaseHTTPMiddleware):
+    """
+    Attach the Keycloak JWT tokens to the user.
+
+    Gets the Keycloak JWT tokens from the request cookies
+    and attaches them to the user. If the token is expired,
+    attempt to refresh it using the refresh token.
+    """
+
+    async def dispatch(self, request: Request, call_next):
+        user = None
+        new_token = None
+        new_user = None
+        try:
+            try:
+                new_user, current_user = await self._refresh_user(request)
+                user = new_user or current_user
+            except (
+                AuthManagerRefreshTokenExpiredException,
+                ExpiredSignatureError,
+                InvalidTokenError,
+                HTTPException,
+            ):
+                new_token = ""
+
+            if user is not None:
+                request.state.user = user
+
+                user_injected = getattr(
+                    core_api_security,
+                    "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+                    None,
+                )
+                if user_injected is not None:
+                    request.state.user_authenticated_via = user_injected
+
+            response = await call_next(request)
+
+            if new_user or new_token is not None:
+                secure = request.base_url.scheme == "https" or bool(conf.get("api", "ssl_cert", fallback=""))
+                cookie_path = get_cookie_path()
+                if new_token == "":
+                    response.set_cookie(
+                        COOKIE_NAME_JWT_TOKEN,
+                        new_token,
+                        path=cookie_path,
+                        httponly=True,
+                        secure=secure,
+                        samesite="lax",
+                        max_age=0,
+                    )
+                    if cookie_path != "/":
+                        response.set_cookie(
+                            COOKIE_NAME_JWT_TOKEN,
+                            "",
+                            path="/",
+                            httponly=True,
+                            secure=secure,
+                            samesite="lax",
+                            max_age=0,
+                        )
+                else:
+                    response = await self._set_new_token(new_user, secure, response, cookie_path)
+
+        except HTTPException as exc:

Review Comment:
   Fair — I checked core and you are right. `JWTRefreshMiddleware.dispatch` has the same shape: the `try` opens before `response = await call_next(request)` and the `except HTTPException` closes after it, so the wide scope is inherited rather than introduced here.
   
   That settles it for this PR — being consistent with the middleware you are subclassing is the right default, and I would rather not have the two drift. If the concern is real it applies to core first, so it belongs there rather than in a copy of it. Not blocking on this.
   
   ---
   Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add KeycloakJWTMiddleware to KeycloakAuthManager [airflow]

Posted by "stephen-bracken (via GitHub)" <gi...@apache.org>.
stephen-bracken commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3696691472


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   Agree it is deliberate to logout existing sessions, as any existing sessions will have the `access_token` and `refresh_token` in the Airflow JWT claims, which we want to move to the `_access_token` and `_refresh_token` JWT cookies.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org