Skip to main content

Middleware to allow authorization using Keycloak and Django

Project description

[WIP] Django Keycloak Authorization

Middleware to allow authorization using Keycloak and Django for DRF and Graphene based projects. This package can only be used for projects started from scratch since they override the users management.

Installation

  1. Add django_keycloak to the Django INSTALLED_APPS

  2. Add django_keycloak.middleware.KeycloakMiddleware to the Django `MIDDLEWARE

  3. Change Django AUTHENTICATION_BACKENDS to:

    AUTHENTICATION_BACKENDS = ('django_keycloak.backends.KeycloakAuthenticationBackend',)
    
  4. Add the following configuration to Django settings and replace the values by your own values:

    KEYCLOAK_CONFIG = {
        'SERVER_URL': '<PUBLIC_SERVER_URL>',
        'INTERNAL_URL': <INTERNAL_SERVER_URL>'',
        'REALM': '<REALM_NAME>',
        'CLIENT_ID': '<CLIENT_ID>',
        'CLIENT_SECRET_KEY': '<CLIENT_SECRET_KEY>',
        'CLIENT_ADMIN_ROLE': '<CLIENT_ADMIN_ROLE>',
        'REALM_ADMIN_ROLE': '<REALM_ADMIN_ROLE>',
        'EXEMPT_URIS': [],  # URIS to be ignored by the package
        'GRAPHQL_ENDPOINT': 'graphql/'  # Default graphQL endpoint
    }
    
  5. Override the Django user model on settings:

    AUTH_USER_MODEL = "django_keycloak.KeycloakUserAutoId"
    
  6. If using graphene add the GRAPHQL_ENDPOINT to settings and KeycloakGrapheneMiddleware to the graphene MIDDLEWARE.

  7. Configure Django Rest Framework authentication classes with django_keycloak.authentication.KeycloakAuthentication:

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'django_keycloak.authentication.KeycloakAuthentication'
        ],
        'DEFAULT_RENDERER_CLASSES': [
            'rest_framework.renderers.JSONRenderer',
        ],
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
        'PAGE_SIZE': 100,  # Default to 20
        'PAGINATE_BY_PARAM': 'page_size',
        # Allow client to override, using `?page_size=xxx`.
        'MAX_PAGINATE_BY': 100,
        # Maximum limit allowed when using `?page_size=xxx`.
        'TEST_REQUEST_DEFAULT_FORMAT': 'json'
    }
    

DRY Permissions

The permissions must be set like in other projects. You must set the permissions configuration for each model. Example:

@staticmethod
@authenticated_users
def has_read_permission(request):
    roles = request.remote_user.get('client_roles')

    return True if 'ADMIN' in roles else False

Keycloak users synchronization

The management command sync_keycloak_users must be ran periodically. In order to remove from the local users the ones that are no longer available at keycloak. This command can be called using the task named sync_users_with_keycloak, using celery. Fot that you just need to:

  • Add the task to the CELERY_BEAT_SCHEDULE ìns Django 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 the sync_users queue to the docker-compose celery service:

    command: celery worker -A citibrain_base -B -E -l info -Q backup,celery,sync_users --autoscale=4,1

Attention: This task is only responsible to delete users from local storage. The creation of new users, that are on keycloak, is done when they try to login.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_uw_keycloak-0.8.6.tar.gz (15.0 kB view details)

Uploaded Source

Built Distribution

django_uw_keycloak-0.8.6-py3-none-any.whl (21.0 kB view details)

Uploaded Python 3

File details

Details for the file django_uw_keycloak-0.8.6.tar.gz.

File metadata

  • Download URL: django_uw_keycloak-0.8.6.tar.gz
  • Upload date:
  • Size: 15.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.7

File hashes

Hashes for django_uw_keycloak-0.8.6.tar.gz
Algorithm Hash digest
SHA256 b80d9a62c4c10e42931e22e7940ebc1d25c6122670e1e0d08b3e0e8b220cb7f4
MD5 2ed3a9ed3c514234e666d6570ff0470a
BLAKE2b-256 428ea318f4a85487422cb8b634fc222e1bdc292a342de2213da29862009d8e60

See more details on using hashes here.

File details

Details for the file django_uw_keycloak-0.8.6-py3-none-any.whl.

File metadata

  • Download URL: django_uw_keycloak-0.8.6-py3-none-any.whl
  • Upload date:
  • Size: 21.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.10.0 pkginfo/1.8.2 requests/2.27.1 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.7

File hashes

Hashes for django_uw_keycloak-0.8.6-py3-none-any.whl
Algorithm Hash digest
SHA256 2ca91eb4ebca518fe0a0cba28b48ea48de4531e10259feda7a77365ba9d0fab7
MD5 cb3cf97105e301180973cf8f90a2b586
BLAKE2b-256 50a1e7e8594dae332c8e558b77706f8ee396714932a88349df1b4a3b7bbb792b

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page