Package: django-uw-keycloak
Django Keycloak AuthorizationMiddleware to allow authorization using Keycloak and Django for django-rest-framework (DRF) and Graphene-based projects.
This package should only be used in projects starting from scratch, since it overrides the users' management.InstallationAdd the module to your environmentWith PIP:pipinstalldjango-uw-keycloakBy compiling from source:gitclonehttps://github.com/urbanplatform/django-keycloak-auth&&\cddjango-keycloak-auth&&\python3setup.pyinstallAdddjango_keycloakto the Django project'sINSTALLED_APPSset in thesettingsfileAdddjango_keycloak.middleware.KeycloakMiddlewareto the DjangoMIDDLEWAREset in thesettingsfileIn your Django project'ssettingsfile, change the DjangoAUTHENTICATION_BACKENDSto:AUTHENTICATION_BACKENDS=('django_keycloak.backends.KeycloakAuthenticationBackend',)Add the following configuration to Django settings and replace the values with your own configuration attributes:KEYCLOAK_CONFIG={# The Keycloak's Public Server URL (e.g. http://localhost:8080)'SERVER_URL':'<PUBLIC_SERVER_URL>',# The Keycloak's Internal URL# (e.g. http://keycloak:8080 for a docker service named keycloak)# Optional: Default is SERVER_URL'INTERNAL_URL':'<INTERNAL_SERVER_URL>',# Override for default Keycloak's base path# Default is '/auth/''BASE_PATH':'/auth/',# The name of the Keycloak's realm'REALM':'<REALM_NAME>',# The ID of this client in the above Keycloak realm'CLIENT_ID':'<CLIENT_ID>'# The secret for this confidential client'CLIENT_SECRET_KEY':'<CLIENT_SECRET_KEY>',# The name of the admin role for the client'CLIENT_ADMIN_ROLE':'<CLIENT_ADMIN_ROLE>',# The name of the admin role for the realm'REALM_ADMIN_ROLE':'<REALM_ADMIN_ROLE>',# Regex formatted URLs to skip authentication'EXEMPT_URIS':[],# Flag if the token should be introspected or decoded (default is False)'DECODE_TOKEN':False,# Flag if the audience in the token should be verified (default is True)'VERIFY_AUDIENCE':True,# Flag if the user info has been included in the token (default is True)'USER_INFO_IN_TOKEN':True,# Flag to show the traceback of debug logs (default is False)'TRACE_DEBUG_LOGS':False,# The token prefix that is expected in Authorization header (default is 'Bearer')'TOKEN_PREFIX':'Bearer'}Override the Django user model in thesettingsfile:AUTH_USER_MODEL="django_keycloak.KeycloakUserAutoId"Configure Django-Rest-Framework authentication classes withdjango_keycloak.authentication.KeycloakAuthentication:REST_FRAMEWORK={# ... other rest framework settings.'DEFAULT_AUTHENTICATION_CLASSES':['django_keycloak.authentication.KeycloakAuthentication'],}CustomizationServer URLsTo customise Keycloak's URL path, setBASE_PATH(for example/my_pathor/) as follows:SERVER_URL/auth/admin/...toSERVER_URL/my_path/admin/...SERVER_URL/auth/realms/...toSERVER_URL/realms/...If your OAuth clients (web or mobile app) use a different URL than your Django service, specify the public URL (https://oauth.example.com) inSERVER_URLand the internal URL (http://keycloak.local) inINTERNAL_URL.DRY PermissionsThe permissions must be set like in other projects. You must set the
permissions configuration for each model. Example:@staticmethod@authenticated_usersdefhas_read_permission(request):roles=request.remote_user.get('client_roles')returnTrueif'ADMIN'inroleselseFalseKeycloak users synchronizationThe management commandsync_keycloak_usersmust be ran periodically, in
order to remove from the users no longer available at
Keycloak from the local users. This command can be called using the task namedsync_users_with_keycloak, using Celery. Fot that, you just need to:Add the task to theCELERY_BEAT_SCHEDULEìn the Django project's settings:CELERY_BEAT_SCHEDULE={'sync_users_with_keycloak':{'task':'django_keycloak.tasks.sync_users_with_keycloak','schedule':timedelta(hours=24),'options':{'queue':'sync_users'}},}Add thesync_usersqueue to thedocker-compose'sceleryservice:command: celery worker -A citibrain_base -B -E -l info -Q backup,celery,sync_users --autoscale=4,1Attention:This task is only responsible to delete users from local
storage. The creation of new users, on Keycloak, is done when they
try to login.NotesSupport for celery 5: from version 0.7.4 on we should use celery 5 for the user sync. This implies running celery withcelery -A app worker ...instead ofcelery worker -A app ...Contactdjango-keycloak-auth [at] googlegroups [dot] com