Code Monkey home page Code Monkey logo

djangorestframework-keycloak's Introduction

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

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/",
    "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

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.

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.

djangorestframework-keycloak's People

Contributors

sascharau avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

rekonas-com

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.