urbanplatform / django-keycloak-auth

Middleware to allow authorization using Keycloak and Django for django-rest-framework (DRF). This package should only be used in projects starting from scratch, since it overrides the users' management.
MIT License
33 stars 14 forks source link

Keycloak 401 on reading user info #68

Closed moritz89 closed 1 year ago

moritz89 commented 1 year ago

Describe the bug Keycloak 401 error after a few minutes when trying to access the Keycloak API

To Reproduce Steps to reproduce the behavior:

  1. Read user info from KeycloakUser
  2. Wait 5 minutes
  3. Read user info from KeylcoakUser

Expected behavior No exceoption and email, name returned

Additional context Problem is that the refresh token is not refreshed. The KeycloakAdmin class has to be configured to get a refresh token and update the access token.

moritz89 commented 1 year ago

The relevant patch to fix the issue:

From 62ab0b96af3f150797c454527ed661e4bfa92c1e Mon Sep 17 00:00:00 2001
From: Moritz Ulmer <moritz.ulmer@posteo.de>
Date: Tue, 14 Feb 2023 09:37:40 +0000
Subject: [PATCH] 507-fix-fetching-user-details-after-timeout

Why:

- Allow Keycloak admin queries to be made after initial deployment

This change addresses the need by:

- Refreshing tokens by default for all HTTP method calls in KC-admin

Closes #507
---
 src/django_keycloak/config.py    | 4 ++++
 src/django_keycloak/connector.py | 1 +
 2 files changed, 5 insertions(+)

diff --git a/src/django_keycloak/config.py b/src/django_keycloak/config.py
index b4a08f25..b3806bad 100644
--- a/src/django_keycloak/config.py
+++ b/src/django_keycloak/config.py
@@ -39,6 +39,10 @@ class Settings:
     USER_INFO_IN_TOKEN: Optional[bool] = True
     # Flag to show the traceback of debug logs
     TRACE_DEBUG_LOGS: Optional[bool] = False
+    # For the KeycloakAdmin, which HTTP methods to refresh the token for
+    AUTO_REFRESH_TOKEN: Optional[List[str]] = field(
+        default_factory=lambda: ["get", "put", "post", "delete"]
+    )
     # The token prefix
     TOKEN_PREFIX: Optional[str] = "Bearer"
     # Derived setting of the SERVER/INTERNAL_URL and BASE_PATH
diff --git a/src/django_keycloak/connector.py b/src/django_keycloak/connector.py
index d83e4173..26d00fac 100644
--- a/src/django_keycloak/connector.py
+++ b/src/django_keycloak/connector.py
@@ -76,4 +76,5 @@ lazy_keycloak_admin = LazyKeycloakAdmin(
     client_id=settings.CLIENT_ID,
     realm_name=settings.REALM,
     client_secret_key=settings.CLIENT_SECRET_KEY,
+    auto_refresh_token=settings.AUTO_REFRESH_TOKEN,
 )
-- 
github-actions[bot] commented 1 year ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] commented 1 year ago

This issue was closed because it has been stalled for 7 days with no activity.