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

Installation

  1. Add the module to your environment

    • With PIP:

      pip install django-uw-keycloak
      
    • By compiling from source:

      git clone https://github.com/urbanplatform/django-keycloak-auth && \
      cd django-keycloak-auth && \
      python3 setup.py install
      
  2. Add django_keycloak to the Django project's INSTALLED_APPS set in the settings file

  3. Add django_keycloak.middleware.KeycloakMiddleware to the Django MIDDLEWARE set in the settings file

  4. In your Django project's settings file, change the Django AUTHENTICATION_BACKENDS to:

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

    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
    }
    
  6. Override the Django user model in the settings file:

    AUTH_USER_MODEL = "django_keycloak.KeycloakUserAutoId"
    
  7. If you are using Graphene, add the GRAPHQL_ENDPOINT to settings and KeycloakGrapheneMiddleware to the Graphene's MIDDLEWARE.

  8. 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 users no longer available at Keycloak from the local users. 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 ì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 the sync_users queue to the docker-compose's 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, on Keycloak, is done when they try to login.

Notes

Support for celery 5: from version 0.7.4 on we should use celery 5 for the user sync. This implies running celery with celery -A app worker ... instead of celery worker -A app ...

Contact

django-keycloak-auth [at] googlegroups [dot] com

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-1.2.0.tar.gz (17.9 kB view details)

Uploaded Source

Built Distribution

django_uw_keycloak-1.2.0-py3-none-any.whl (24.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_uw_keycloak-1.2.0.tar.gz
  • Upload date:
  • Size: 17.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.15

File hashes

Hashes for django_uw_keycloak-1.2.0.tar.gz
Algorithm Hash digest
SHA256 49487409f478f25fb6bfd2d84c71dca7deb68e925b14179d018a5ab947128fea
MD5 1ce5301fa7794ef659923ad4541adc61
BLAKE2b-256 7af6da12412203024d156afa491a298359400a16cdefc8f1316889e211a473ec

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_uw_keycloak-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eb5ada461db10a0e867e7f0bc230169e52865811d6a821cb71198e1ffb5ac2f8
MD5 56883c5e9fe7b97598bcbbe8d7f057af
BLAKE2b-256 f311f5ec80d8a89961f7d39e6fae4cd0111e92add77dbd769fe9a2786fb4eab2

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