You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "fediabdelhedi (via GitHub)" <gi...@apache.org> on 2025/10/14 15:11:29 UTC

[PR] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

fediabdelhedi opened a new pull request, #56624:
URL: https://github.com/apache/airflow/pull/56624

   
   
   ## What
   Implements automatic token refresh when Keycloak access token expires.
   
   ## Why
   Fixes #56614 - Users receive 500 Internal Server Error after token lifetime (5 minutes) expires. The Keycloak provider was not implementing OAuth2 refresh token flow.
   
   ## How
   1. **Added `_refresh_access_token()` method** that:
      - Retrieves refresh token from the user object
      - Calls Keycloak token endpoint with `grant_type=refresh_token`
      - Updates user's access token and refresh token
      - Includes comprehensive error handling and logging
   
   2. **Modified `_is_authorized()` to**:
      - Catch 401 Unauthorized responses (token expired)
      - Attempt token refresh using `_refresh_access_token()`
      - Retry the authorization check with the new token
      - Provide clear error messages if refresh fails
   
   3. **Modified `_is_batch_authorized()` to**:
      - Apply the same token refresh logic for batch authorization checks
      - Ensure consistency across authorization methods
   
   ## Testing
   - [x] Code follows Airflow coding standards
   - [x] Logic verified against OAuth2 refresh token specification
   - [ ] Manual testing with Keycloak (requires dedicated test environment)
   
   **Note:** I don't currently have a Keycloak test environment set up. The implementation follows the OAuth2 standard refresh token flow and matches the pattern used in similar auth providers. Happy to add tests or make adjustments based on reviewer feedback!
   
   ## Impact
   - Users will remain logged in after token expiration
   - No more 500 errors after 5 minutes of inactivity
   - Seamless user experience with automatic token renewal
   
   Closes: #56614
   
   ---
   **^ Add meaningful description above**
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
   


-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -270,6 +270,62 @@
             realm_name=realm,
         )
 
+    def _refresh_access_token(self, user: KeycloakAuthManagerUser) -> bool:
+        """
+        Refresh expired access token using refresh token.
+        
+        Args:
+            user: The user whose token needs to be refreshed
+        
+        Returns:
+            bool: True if refresh succeeded, False otherwise
+        """
+        if not user.refresh_token:
+            log.warning("No refresh token available for user %s", user.get_id())
+            return False
+        
+        realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
+        server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY)
+        client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY)
+        client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY)
+        
+        token_url = self._get_token_url(server_url, realm)
+        
+        try:
+            response = requests.post(
+                token_url,
+                data={
+                    "grant_type": "refresh_token",
+                    "refresh_token": user.refresh_token,
+                    "client_id": client_id,
+                    "client_secret": client_secret,
+                },
+                timeout=10,
+            )
+
+            if response.status_code == 200:
+                tokens = response.json()
+
+                user.access_token = tokens["access_token"]
+
+                if "refresh_token" in tokens:
+                    user.refresh_token = tokens["refresh_token"]
+
+                log.info("Successfully refreshed access token for user %s", user.get_id())
+                return True
+            else:
+                log.error(
+                    "Failed to refresh token for user %s: %s - %s",
+                    user.get_id(),
+                    response.status_code,
+                    response.text,

Review Comment:
   If I remove the logs , will this contribution get approved ?



-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #56624:
URL: https://github.com/apache/airflow/pull/56624#discussion_r2429901506


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -270,6 +270,62 @@
             realm_name=realm,
         )
 
+    def _refresh_access_token(self, user: KeycloakAuthManagerUser) -> bool:
+        """
+        Refresh expired access token using refresh token.
+        
+        Args:
+            user: The user whose token needs to be refreshed
+        
+        Returns:
+            bool: True if refresh succeeded, False otherwise
+        """
+        if not user.refresh_token:
+            log.warning("No refresh token available for user %s", user.get_id())
+            return False
+        
+        realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
+        server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY)
+        client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY)
+        client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY)
+        
+        token_url = self._get_token_url(server_url, realm)
+        
+        try:
+            response = requests.post(
+                token_url,
+                data={
+                    "grant_type": "refresh_token",
+                    "refresh_token": user.refresh_token,
+                    "client_id": client_id,
+                    "client_secret": client_secret,
+                },
+                timeout=10,
+            )
+
+            if response.status_code == 200:
+                tokens = response.json()
+
+                user.access_token = tokens["access_token"]
+
+                if "refresh_token" in tokens:
+                    user.refresh_token = tokens["refresh_token"]
+
+                log.info("Successfully refreshed access token for user %s", user.get_id())
+                return True
+            else:
+                log.error(
+                    "Failed to refresh token for user %s: %s - %s",
+                    user.get_id(),
+                    response.status_code,
+                    response.text,

Review Comment:
   ## Clear-text logging of sensitive information
   
   This expression logs [sensitive data (secret)](1) as clear text.
   This expression logs [sensitive data (secret)](2) as clear text.
   
   [Show more details](https://github.com/apache/airflow/security/code-scanning/536)



-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -270,6 +270,62 @@
             realm_name=realm,
         )
 
+    def _refresh_access_token(self, user: KeycloakAuthManagerUser) -> bool:
+        """
+        Refresh expired access token using refresh token.
+        
+        Args:
+            user: The user whose token needs to be refreshed
+        
+        Returns:
+            bool: True if refresh succeeded, False otherwise
+        """
+        if not user.refresh_token:
+            log.warning("No refresh token available for user %s", user.get_id())
+            return False
+        
+        realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
+        server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY)
+        client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY)
+        client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY)
+        
+        token_url = self._get_token_url(server_url, realm)
+        
+        try:
+            response = requests.post(
+                token_url,
+                data={
+                    "grant_type": "refresh_token",
+                    "refresh_token": user.refresh_token,
+                    "client_id": client_id,
+                    "client_secret": client_secret,
+                },
+                timeout=10,
+            )
+
+            if response.status_code == 200:
+                tokens = response.json()
+
+                user.access_token = tokens["access_token"]
+
+                if "refresh_token" in tokens:
+                    user.refresh_token = tokens["refresh_token"]
+
+                log.info("Successfully refreshed access token for user %s", user.get_id())
+                return True
+            else:
+                log.error(
+                    "Failed to refresh token for user %s: %s - %s",
+                    user.get_id(),
+                    response.status_code,
+                    response.text,

Review Comment:
   Ye thats unfortunate ... hopefully I work on another problem , ty so much any way



-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #56624:
URL: https://github.com/apache/airflow/pull/56624#issuecomment-3402354955

   Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
   Here are some useful points:
   - Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
   - In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example DAG that shows how users should use it.
   - Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
   - Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
   - Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
   - Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
   - Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
   Apache Airflow is a community-driven project and together we are making it better 🚀.
   In case of doubts contact the developers at:
   Mailing List: dev@airflow.apache.org
   Slack: https://s.apache.org/airflow-slack
   


-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck closed pull request #56624: Fix: Implement token refresh for Keycloak provider (#56614)
URL: https://github.com/apache/airflow/pull/56624


-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -270,6 +270,62 @@
             realm_name=realm,
         )
 
+    def _refresh_access_token(self, user: KeycloakAuthManagerUser) -> bool:
+        """
+        Refresh expired access token using refresh token.
+        
+        Args:
+            user: The user whose token needs to be refreshed
+        
+        Returns:
+            bool: True if refresh succeeded, False otherwise
+        """
+        if not user.refresh_token:
+            log.warning("No refresh token available for user %s", user.get_id())
+            return False
+        
+        realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
+        server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY)
+        client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY)
+        client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY)
+        
+        token_url = self._get_token_url(server_url, realm)
+        
+        try:
+            response = requests.post(
+                token_url,
+                data={
+                    "grant_type": "refresh_token",
+                    "refresh_token": user.refresh_token,
+                    "client_id": client_id,
+                    "client_secret": client_secret,
+                },
+                timeout=10,
+            )
+
+            if response.status_code == 200:
+                tokens = response.json()
+
+                user.access_token = tokens["access_token"]
+
+                if "refresh_token" in tokens:
+                    user.refresh_token = tokens["refresh_token"]
+
+                log.info("Successfully refreshed access token for user %s", user.get_id())
+                return True
+            else:
+                log.error(
+                    "Failed to refresh token for user %s: %s - %s",
+                    user.get_id(),
+                    response.status_code,
+                    response.text,

Review Comment:
   See my [comment](https://github.com/apache/airflow/pull/56624#issuecomment-3403208081) below.



-- 
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] Fix: Implement token refresh for Keycloak provider (#56614) [airflow]

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

   Heads-up on this one. Refresh token functionality will be refactored very soon in Airflow. And the new version of refresh token should solve the issue you are experiencing and trying to solve. You can find the PR here: https://github.com/apache/airflow/pull/55506. 


-- 
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