Skip to main content

Keycloak authentication plugin for Django REST Framework

Project description

In this project, we implement authentication using the Authorization Code Flow with Keycloak as the identity and access management service. Here is how the authentication flow is structured:

  1. Frontend Responsibility:

    • User Registration and Login: The frontend handles user registration and login through Keycloak, facilitating a seamless user experience.

  2. Backend Responsibility:

    • Token Validation: Once a user is authenticated, the backend takes over by validating the JWT (JSON Web Token) from the header of each incoming request to ensure it is valid and secure.

This approach allows us to keep the backend implementation relatively simple, focusing mainly on token validation, while leveraging Keycloak’s robust authentication and authorization features through the frontend.

Install

pip install drf-keycloak

Settings

You can find a selection of variables in drf_keycloak.settings.py, just overwrite them in the Django settings.

KEYCLOAK_CONFIG = {
    "SERVER_URL": "http://localhost:8080/realms/master",
    "REALM": "master",
    "CLIENT_ID": "account",
    "CLIENT_SECRET": None,
    "AUDIENCE": None,
    "ALGORITHM": "RS256",
    "ISSUER": "http://localhost:8080/realms/master",
    "PERMISSION_PATH": "resource_access.account.roles",
    "USER_ID_FIELD": "username",
    "USER_ID_CLAIM": "preferred_username",
    "VERIFY_SIGNATURE": True,
    # user mapping
    # django keys, keycloak keys
    "CLAIM_MAPPING": {
        "first_name": "given_name",
        "last_name": "family_name",
        "email": "email",
        "username": "preferred_username",
    },
}

Enable

Add keycloak to INSTALLED_APPS.

INSTALLED_APPS = [
    "django.contrib.auth",
    # ...
    "drf_keycloak"
]

Add drf_keycloak.authentication.KeycloakAuthBackend to DRF settings

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        # ...
        "drf_keycloak.authentication.KeycloakAuthBackend",
        # ...
    ],
}

Permissions

To create permissions for your API follow the example in HasViewProfilePermission in drf_keycloak.permissions.py.

Use it as usual…

from drf_keycloak.permissions import HasPermission

class ExamplePermission(HasPermission):
    permission = "view-profile"


class UserApi(generics.RetrieveAPIView):
    permission_classes = [ExamplePermission]

Middleware

For security reasons, use the optional middleware in drf_keycloak.middleware.HeaderMiddleware at the top of the settings.

MIDDLEWARE = [
    "drf_keycloak.middleware.HeaderMiddleware",
    # ...
]

You should also look at Mozilla’s django-csp package.

OpenAPI Schema with drf-spectacular

In any apps.py or file that is loaded at startup

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    """app config"""

    default_auto_field = "django.db.models.BigAutoField"
    name = "myapp"

    def ready(self):
        import drf_keycloak.schema  # noqa: E402

Thanks

Thanks to django-rest-framework-simplejwt, the code was inspirational for this package.

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

drf_keycloak-1.0.3.tar.gz (14.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_keycloak-1.0.3-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

Details for the file drf_keycloak-1.0.3.tar.gz.

File metadata

  • Download URL: drf_keycloak-1.0.3.tar.gz
  • Upload date:
  • Size: 14.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for drf_keycloak-1.0.3.tar.gz
Algorithm Hash digest
SHA256 8d29928d7a2aa03d048581f6a41673df72b0796b5ba54c614c6ba1d12e7c2d8f
MD5 ddb19d6f386be9208921698f9d55c115
BLAKE2b-256 08f9596c1201f95ff090c926b5f9b0ba2c70eacd191f017f193b6c0adf7eec7f

See more details on using hashes here.

File details

Details for the file drf_keycloak-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: drf_keycloak-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 11.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for drf_keycloak-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 92ff802aa871f852ec5ba7c409f9995bc39332f2ca71555175e6139e03d35dda
MD5 ed96972ba582a92bb66601b8229e4a49
BLAKE2b-256 07aeab1756533de13a3224c3ed302e644cc835ce5c69873edd22fd824eeddc55

See more details on using hashes here.

Supported by

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