=================================================
Keycloak Authentication for Django Rest Framework
=================================================
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
_______
.. code-block:: bash
pip install drf-keycloak
Settings
--------
You can find a selection of variables in ``drf_keycloak.settings.py``, just overwrite them in the Django settings.
.. code-block:: python
KEYCLOAK_CONFIG = {
"SERVER_URL": "http://localhost:8080/",
"REALM": "master",
"CLIENT_ID": "account",
"CLIENT_SECRET": None,
"AUDIENCE": None,
"ALGORITHM": "RS256",
"ISSUER": "http://localhost:8080/realms/master",
"VERIFY_TOKENS_WITH_KEYCLOAK": False,
"PERMISSION_PATH": "resource_access.account.roles",
"USER_ID_FIELD": "username",
"USER_ID_CLAIM": "preferred_username",
# user mapping
# django keys, keycloak keys
"CLAIM_MAPPING": {
"first_name": "given_name",
"last_name": "family_name",
"email": "email",
"username": "preferred_username",
},
}
By setting the variable
.. code-block:: python
KEYCLOAK_CONFIG = {
# ...
"VERIFY_TOKENS_WITH_KEYCLOAK": True
# ...
}
This means that the token is validated with the Keycloak API and locally.
Enable
******
Add ``keycloak`` to ``INSTALLED_APPS``.
.. code-block:: python
INSTALLED_APPS = [
"django.contrib.auth",
# ...
"drf_keycloak"
]
Add ``drf_keycloak.authentication.KeycloakAuthBackend`` to DRF settings
.. code-block:: python
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...
.. code-block:: python
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.
.. code-block:: python
MIDDLEWARE = [
"drf_keycloak.middleware.HeaderMiddleware",
# ...
]
You should also look at Mozilla's `django-csp <https://github.com/mozilla/django-csp>`_ package.
OpenAPI Schema with drf-spectacular
***********************************
In any ``apps.py`` or file that is loaded at startup
.. code-block:: python
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 <https://github.com/jazzband/djangorestframework-simplejwt>`_, the code was inspirational for this package.
Raw data
{
"_id": null,
"home_page": "https://github.com/sascharau/djangorestframework-keycloak",
"name": "drf-keycloak",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": null,
"author": "Sascha Rau",
"author_email": "ideal3000developer@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/6c/f4/f436b6bff69623c6ec0330599007b396b3cbaac1e849e04882127469c616/drf-keycloak-1.0.1.tar.gz",
"platform": null,
"description": "=================================================\nKeycloak Authentication for Django Rest Framework\n=================================================\n\nIn 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:\n\n1. **Frontend Responsibility**:\n\n - **User Registration and Login**: The frontend handles user registration and login through Keycloak, facilitating a seamless user experience.\n\n2. **Backend Responsibility**:\n\n - **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.\n\nThis 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.\n\nInstall\n_______\n\n.. code-block:: bash\n\n pip install drf-keycloak\n\n\n\nSettings\n--------\n\nYou can find a selection of variables in ``drf_keycloak.settings.py``, just overwrite them in the Django settings.\n\n.. code-block:: python\n\n KEYCLOAK_CONFIG = {\n \"SERVER_URL\": \"http://localhost:8080/\",\n \"REALM\": \"master\",\n \"CLIENT_ID\": \"account\",\n \"CLIENT_SECRET\": None,\n \"AUDIENCE\": None,\n \"ALGORITHM\": \"RS256\",\n \"ISSUER\": \"http://localhost:8080/realms/master\",\n \"VERIFY_TOKENS_WITH_KEYCLOAK\": False,\n \"PERMISSION_PATH\": \"resource_access.account.roles\",\n \"USER_ID_FIELD\": \"username\",\n \"USER_ID_CLAIM\": \"preferred_username\",\n\n # user mapping\n # django keys, keycloak keys\n \"CLAIM_MAPPING\": {\n \"first_name\": \"given_name\",\n \"last_name\": \"family_name\",\n \"email\": \"email\",\n \"username\": \"preferred_username\",\n },\n }\n\nBy setting the variable\n\n.. code-block:: python\n\n KEYCLOAK_CONFIG = {\n # ...\n \"VERIFY_TOKENS_WITH_KEYCLOAK\": True\n # ...\n }\n\nThis means that the token is validated with the Keycloak API and locally.\n\nEnable\n******\n\nAdd ``keycloak`` to ``INSTALLED_APPS``.\n\n.. code-block:: python\n\n INSTALLED_APPS = [\n \"django.contrib.auth\",\n # ...\n \"drf_keycloak\"\n ]\n\nAdd ``drf_keycloak.authentication.KeycloakAuthBackend`` to DRF settings\n\n.. code-block:: python\n\n REST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": [\n # ...\n \"drf_keycloak.authentication.KeycloakAuthBackend\",\n # ...\n ],\n }\n\nPermissions\n***********\n\nTo create permissions for your API follow the example in ``HasViewProfilePermission`` in ``drf_keycloak.permissions.py``.\n\nUse it as usual...\n\n.. code-block:: python\n\n from drf_keycloak.permissions import HasPermission\n\n class ExamplePermission(HasPermission):\n permission = \"view-profile\"\n\n\n class UserApi(generics.RetrieveAPIView):\n permission_classes = [ExamplePermission]\n\nMiddleware\n**********\n\nFor security reasons, use the optional middleware in ``drf_keycloak.middleware.HeaderMiddleware`` at the top of the settings.\n\n.. code-block:: python\n\n MIDDLEWARE = [\n \"drf_keycloak.middleware.HeaderMiddleware\",\n # ...\n ]\n\nYou should also look at Mozilla's `django-csp <https://github.com/mozilla/django-csp>`_ package.\n\nOpenAPI Schema with drf-spectacular\n***********************************\n\nIn any ``apps.py`` or file that is loaded at startup\n\n.. code-block:: python\n\n from django.apps import AppConfig\n\n class MyAppConfig(AppConfig):\n \"\"\"app config\"\"\"\n\n default_auto_field = \"django.db.models.BigAutoField\"\n name = \"myapp\"\n\n def ready(self):\n import drf_keycloak.schema # noqa: E402\n\nThanks\n******\n\nThanks to `django-rest-framework-simplejwt <https://github.com/jazzband/djangorestframework-simplejwt>`_, the code was inspirational for this package.\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Keycloak authentication plugin for Django REST Framework",
"version": "1.0.1",
"project_urls": {
"Homepage": "https://github.com/sascharau/djangorestframework-keycloak"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "df7ab0ecee8cd67ddca5773a054840f3cff02d1a80cd1cc6392491ab83d0430b",
"md5": "2624ea009263d3b4b550f40adb5b8290",
"sha256": "c4ea7717677f134b2bd9e5e3d988959f0177e20ac90ccabcd168476b91706c3c"
},
"downloads": -1,
"filename": "drf_keycloak-1.0.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "2624ea009263d3b4b550f40adb5b8290",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 10724,
"upload_time": "2024-11-12T09:30:32",
"upload_time_iso_8601": "2024-11-12T09:30:32.053464Z",
"url": "https://files.pythonhosted.org/packages/df/7a/b0ecee8cd67ddca5773a054840f3cff02d1a80cd1cc6392491ab83d0430b/drf_keycloak-1.0.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "6cf4f436b6bff69623c6ec0330599007b396b3cbaac1e849e04882127469c616",
"md5": "87031adb35e6b68bed59ff3df29cfff4",
"sha256": "85cd5d123904bf35795fcbc77bf208d3be1d4823bea7d4686e6849df5e5469be"
},
"downloads": -1,
"filename": "drf-keycloak-1.0.1.tar.gz",
"has_sig": false,
"md5_digest": "87031adb35e6b68bed59ff3df29cfff4",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 14458,
"upload_time": "2024-11-12T09:30:34",
"upload_time_iso_8601": "2024-11-12T09:30:34.342626Z",
"url": "https://files.pythonhosted.org/packages/6c/f4/f436b6bff69623c6ec0330599007b396b3cbaac1e849e04882127469c616/drf-keycloak-1.0.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-12 09:30:34",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "sascharau",
"github_project": "djangorestframework-keycloak",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"tox": true,
"lcname": "drf-keycloak"
}