Skip to content

Getting started

Install

pip install drf-keycloak

Enable the app

Add drf_keycloak to INSTALLED_APPS:

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

Register the authentication backend

Add KeycloakAuthBackend to the DRF settings:

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

Point it at your realm

The minimum configuration is the realm URL. Everything else has a default — see Configuration for the full list.

KEYCLOAK_CONFIG = {
    "ISSUER": "https://keycloak.example.com/realms/myrealm",
    "CLIENT_ID": "my-api",
    "AUDIENCE": "my-api",
}

Set AUDIENCE

With AUDIENCE left at None the aud claim is not checked, so a token minted for any client in the same realm is accepted by your API. See Audience.

Make a request

Send the access token as a bearer token:

curl -H "Authorization: Bearer $ACCESS_TOKEN" https://api.example.com/profile/

On success the token's claims are mapped onto a Django user (created on first login, and re-synced from the token on every subsequent login — see CLAIM_MAPPING), which is then available as request.user.

A missing Authorization header leaves the request anonymous so other authenticators still get their turn; a present-but-invalid token is rejected with 401. The details are in Behavior on invalid tokens.