Skip to main content

Middleware to allow authorization using Keycloak and Django

Project description

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 to Django settings:

    KEYCLOAK_CONFIG = {
        'SERVER_URL': 'https://keycloak.staging.ubiwhere.com',
        'INTERNAL_URL': 'https://keycloak.staging.ubiwhere.com',
        'REALM': 'django',
        'CLIENT_ID': 'api',
        'CLIENT_SECRET_KEY': '0414b857-8430-4fbb-b86a-62bc398f37ea',
        'CLIENT_ADMIN_ROLE': 'admin',
        'REALM_ADMIN_ROLE': 'admin',
        'EXEMPT_URIS': [],
        'GRAPHQL_ENDPOINT': 'graphql/'
    }
    
  5. Override the Django user model on settings:

    AUTH_USER_MODEL = "django_keycloak.KeycloakUser"
    
  6. If using graphene add the GRAPHQL_ENDPOINT to settings and ``KeycloakGrapheneMiddleware to the grapheneMIDDLEWARE`

Django Admin

The Django superuser that can be used for the Django Admin login, must created with the normal management command python manage.py createsuperuser. But first you must create this user on keycloak and set a client admin role and realm admin role like the CLIENT_ADMIN_ROLE and REALM_ADMIN_ROLE that were added on settings previously.

Django Rest Framework

In the Django settings the the Rest Framework settings can't have any Authorization values (used in other projects). Example:

```json
# Rest framework settings
REST_FRAMEWORK = {
    '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 the the permissions configuration for each model. Example:

```json
@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.4.tar.gz (10.2 kB view details)

Uploaded Source

Built Distribution

django_uw_keycloak-0.4-py3-none-any.whl (12.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_uw_keycloak-0.4.tar.gz
  • Upload date:
  • Size: 10.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.6.12

File hashes

Hashes for django_uw_keycloak-0.4.tar.gz
Algorithm Hash digest
SHA256 4dcc2492f0050640fa061d0641b1db8f1f0f31bcf4180b42dbf6732d6870211a
MD5 639c523d98717e08f8c63dd3c058e4df
BLAKE2b-256 3132a3f527b417a5970ae4eaf7c54fbbf3d38af726c15a456f18d9cb7be00ad9

See more details on using hashes here.

File details

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

File metadata

  • Download URL: django_uw_keycloak-0.4-py3-none-any.whl
  • Upload date:
  • Size: 12.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.25.1 setuptools/52.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.6.12

File hashes

Hashes for django_uw_keycloak-0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 9d7020826205ee5b2a6ed075096767b9afbaf346b69d00975611c8ad455ab62b
MD5 cc6a463f38bec4f1256bb7756790d50f
BLAKE2b-256 d89a478456b57e6a8c3afcdf85995020fbe0271a60f15b855272c4cd416088f9

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