python-keycloak package with KeycloakOpenID : logout does not work
Asked Answered
D

2

1

I have a keycloak docker container (pulled image jboss/keycloak ) and a Django 2.2 web container. For integration of django with keycloak social-auth-app-django was used. Login works fine. Now trying to implement logout using python-keycloak following instructions described here:

https://github.com/marcospereirampj/python-keycloak :

   from keycloak import KeycloakOpenID

    keycloak_openid = KeycloakOpenID(server_url="http://<my IP>:8080/auth/",
                        client_id="<client_id>",
                        realm_name="<my realm name>",
                        client_secret_key="<my secret>",
                        verify=True)
    config_well_know = keycloak_openid.well_know()
    token = keycloak_openid.token("<username>", "<password>")
    print(token) # all tokens returned ok

    userinfo = keycloak_openid.userinfo(token['access_token'])
    print ("userinfo:", userinfo) # userinfo returned ok 

    keycloak_openid.logout(token['refresh_token'])

in the container log: Some clients have been not been logged out for user <username> in <my realm name> realm: <client_id> No logout happens, still can browse the site.

What's missing? Thanks

UPDATE Maybe I understood the problem. The token I get from keycloak_openid.token() call is not the token that was generated for me at the moment of login. The only token that can be fed to keycloak_openid.logout() call for it to work is that original token ('refresh_token' key value of the token dict, to be specific). Calling keycloak_openid.refresh_token() also issues a new token which is rejected as logout credential. But the originally issued refresh_token does not seem to be stored anywhere - sessions, cookies or keycloak db. (Note: I did find access_token, it's in the django DB in social_auth_usersocialauth table, but I need refresh_token). However, it's dumped to the console output at the moment of login, so if I copy it and call keycloak_openid.logout() with it, it does logout from keycoak. The question is where can I find that original refresh_token?

Dentil answered 3/12, 2019 at 17:38 Comment(0)
K
2

I used to experience the same issue. What helped was

  1. Going to admin page and location your user in the realm
  2. open your browser's developer console and monitor the networks
  3. Go to sessions tab on keycloak and click log out
  4. Observe which end point is being called and mimic that in your python backend, with proper header in the request.

Hope this helps!

Kailakaile answered 4/12, 2019 at 14:40 Comment(0)
W
0

I understand that this question is outdated, but I managed to logout by this:

  1. Add the following variables to settings.py:
SOCIAL_AUTH_KEYCLOAK_LOGOUT_URL = 'https://your-keycloak/auth/realms/your-realm/openid-connect/logout'

SOCIAL_AUTH_KEYCLOAK_EXTRA_DATA=[("refresh_token","refresh_token")]

Now it will save the refresh token in extra_data.

  1. Add into urlpatterns list in urls.py:

url(r'^logout/$', views.logout, name='logout'),

  1. Add the logout view with communication code to views.py:
from django.contrib.auth import logout as auth_logout
import requests

def logout(request):
    if request.user.is_authenticated:
        user = request.user
        if user.social_auth.filter(provider='keycloak'):
            social = user.social_auth.get(provider='keycloak')
            access_token=social.extra_data['access_token']
            refresh_token=social.extra_data['refresh_token']
            #logger.debug(access_token) # you can view the tokens
            #logger.debug(refresh_token)
            logout_request_data={"client_id": settings.SOCIAL_AUTH_KEYCLOAK_KEY, "refresh_token": refresh_token, "client_secret": settings.SOCIAL_AUTH_KEYCLOAK_SECRET}
            headers={"Authorization" : "Bearer "+access_token,"Content-Type" : "application/x-www-form-urlencoded"}
            result=requests.post(settings.SOCIAL_AUTH_KEYCLOAK_LOGOUT_URL,data=logout_request_data,headers=headers)
    auth_logout(request)
    return redirect('/')

result code will be 204 on success.

Wreak answered 26/1, 2022 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.