Add Keycloak login to a Django app
Add Keycloak login to Django with mozilla-django-oidc, log users out of Keycloak too, and protect a REST API by validating access tokens with PyJWT.
This guide signs users in to a Django app with mozilla-django-oidc, logs them out of Keycloak as well, and protects a Django REST Framework endpoint with access tokens.
Written against Django 6.1.3, mozilla-django-oidc 5.0.2, PyJWT 2.15.1 and Django REST Framework 3.18.3 on Python 3.13 and Keycloak 26.8, checked on 25 November 2026. mozilla-django-oidc 5.0.2 lists Django 4.2 to 5.2 as supported; the code is the same on Django 5.2 LTS.
Replace auth.example.com with your RealmDeploy hostname and acme with your realm.
Create the client in Keycloak
In your realm, open Clients and choose Create client. Use these values, then choose Save:
| Setting | Value |
|---|---|
| Client type | OpenID Connect |
| Client ID | my-app |
| Client authentication | On |
| Authentication flow | Standard flow only. Turn Direct access grants off. |
| Root URL | http://localhost:8000 |
| Valid redirect URIs | http://localhost:8000/oidc/callback/ |
| Valid post logout redirect URIs | http://localhost:8000/ |
| Web origins | Leave empty. The browser never calls Keycloak from JavaScript in this app. |
Copy the Client secret from the client's Credentials tab.
Give your test user an email address (Users, the user, Email). mozilla-django-oidc matches Django users by email and refuses a login without one.
For production, add the same paths on your app's HTTPS address, for example https://app.example.com/oidc/callback/ and https://app.example.com/. Keycloak compares redirect URIs exactly, including the trailing slash.
Environment variables
OIDC_ISSUER=https://auth.example.com/realms/acme
OIDC_RP_CLIENT_ID=my-app
OIDC_RP_CLIENT_SECRET=paste-the-client-secret
API_AUDIENCE=my-apiDjango does not read .env files by itself. Load the file into your shell before you start the server (set -a; . ./.env; set +a), or use the settings tool you already have.
Install
python -m pip install "Django>=6.1" mozilla-django-oidc "pyjwt[crypto]" djangorestframework
django-admin startproject mysite .
python manage.py migrateDjango REST Framework is only needed for Protect an API.
Add login
Add this to the end of the generated settings file:
# --- OpenID Connect login with Keycloak ---
import os
INSTALLED_APPS += [
"mozilla_django_oidc", # must come after django.contrib.auth
"rest_framework", # only for "Protect an API"
]
TEMPLATES[0]["DIRS"] = [BASE_DIR / "templates"]
AUTHENTICATION_BACKENDS = [
"mozilla_django_oidc.auth.OIDCAuthenticationBackend",
"django.contrib.auth.backends.ModelBackend", # keeps /admin/ passwords working
]
OIDC_ISSUER = os.environ["OIDC_ISSUER"]
OIDC_RP_CLIENT_ID = os.environ["OIDC_RP_CLIENT_ID"]
OIDC_RP_CLIENT_SECRET = os.environ["OIDC_RP_CLIENT_SECRET"]
OIDC_RP_SIGN_ALGO = "RS256"
OIDC_OP_AUTHORIZATION_ENDPOINT = f"{OIDC_ISSUER}/protocol/openid-connect/auth"
OIDC_OP_TOKEN_ENDPOINT = f"{OIDC_ISSUER}/protocol/openid-connect/token"
OIDC_OP_USER_ENDPOINT = f"{OIDC_ISSUER}/protocol/openid-connect/userinfo"
OIDC_OP_JWKS_ENDPOINT = f"{OIDC_ISSUER}/protocol/openid-connect/certs"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"
# Log out of Keycloak too (see "Log out")
OIDC_STORE_ID_TOKEN = True
OIDC_OP_LOGOUT_URL_METHOD = "mysite.oidc.keycloak_logout_url"
KEYCLOAK_LOGOUT_ENDPOINT = f"{OIDC_ISSUER}/protocol/openid-connect/logout"
# The audience your API expects in access tokens (see "Protect an API")
API_AUDIENCE = os.environ["API_AUDIENCE"]OIDC_RP_SIGN_ALGO defaults to HS256 in mozilla-django-oidc. Keycloak signs ID tokens with RS256, so set it, together with OIDC_OP_JWKS_ENDPOINT for the realm's public keys. KEYCLOAK_LOGOUT_ENDPOINT and API_AUDIENCE are our own settings, not the library's.
Add the library's routes and a home page:
from django.contrib import admin
from django.urls import include, path
from . import views
urlpatterns = [
path("admin/", admin.site.urls),
path("oidc/", include("mozilla_django_oidc.urls")),
path("", views.home),
]from django.shortcuts import render
def home(request):
return render(request, "home.html"){% if user.is_authenticated %}
<p>Signed in as {{ user.email }}</p>
<form action="{% url 'oidc_logout' %}" method="post">
{% csrf_token %}
<button type="submit">Log out</button>
</form>
{% else %}
<a href="{% url 'oidc_authentication_init' %}">Log in</a>
{% endif %}Run python manage.py runserver, open http://localhost:8000 and choose Log in.
/oidc/authenticate/ sends the browser to Keycloak. /oidc/callback/ exchanges the code, checks the ID token's signature against the realm's keys and its nonce, then reads the user's claims from the userinfo endpoint and finds or creates the Django user with that email.
Protect an API
mozilla-django-oidc ships a DRF class, mozilla_django_oidc.contrib.drf.OIDCAuthentication. It does not validate the token itself: on every request it sends the token to Keycloak's userinfo endpoint and looks up the Django user by email. That costs a network round trip per request, and it never checks the token's audience, so any valid token from the realm gets in. We validate access tokens locally with PyJWT instead: signature against the realm's JWKS, issuer, audience and expiry.
Add an Audience mapper
By default, Keycloak access tokens carry aud: account, and only when the user has roles of the account client. Add your API's audience to the tokens of the client that calls it, here my-app:
- Open Clients, then
my-app, then the Client scopes tab, thenmy-app-dedicated. - Choose Configure a new mapper, then Audience. If the scope already has mappers, choose Add mapper, By configuration, Audience.
- Set Name to
my-api audience, Included Custom Audience tomy-api, Add to access token on and Add to ID token off. Choose Save.
If your API has its own client in Keycloak, choose it under Included Client Audience instead, and set API_AUDIENCE to its client ID.
To check, open the client's Client scopes tab, then the Evaluate sub-tab, pick a user and look at Generated access token: aud should contain my-api.
Validate the token
import jwt
from django.conf import settings
from rest_framework import authentication, exceptions
# Downloads the realm's public keys on first use and caches them.
jwks_client = jwt.PyJWKClient(settings.OIDC_OP_JWKS_ENDPOINT)
class TokenUser:
"""The caller, as described by a verified access token."""
is_authenticated = True
def __init__(self, claims):
self.claims = claims
self.username = claims.get("preferred_username", claims["sub"])
class KeycloakJWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
header = authentication.get_authorization_header(request).split()
if not header or header[0].lower() != b"bearer":
return None # no bearer token: IsAuthenticated answers 401
if len(header) != 2:
raise exceptions.AuthenticationFailed("Invalid Authorization header.")
token = header[1].decode()
try:
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key,
algorithms=["RS256"],
audience=settings.API_AUDIENCE,
issuer=settings.OIDC_ISSUER,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.PyJWTError as exc:
raise exceptions.AuthenticationFailed(f"Invalid token: {exc}")
return TokenUser(claims), claims
def authenticate_header(self, request):
# Makes DRF answer 401 with this header instead of 403.
return 'Bearer realm="api"'Add an endpoint that uses it:
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from .api_auth import KeycloakJWTAuthentication
def home(request):
return render(request, "home.html")
class ApiMe(APIView):
authentication_classes = [KeycloakJWTAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
claims = request.auth # the verified access token's claims
return Response({"sub": claims["sub"], "username": claims.get("preferred_username")})Add its route to urlpatterns:
urlpatterns = [
path("admin/", admin.site.urls),
path("oidc/", include("mozilla_django_oidc.urls")),
path("api/me", views.ApiMe.as_view()),
path("", views.home),
]A caller sends a user's access token issued to my-app:
curl -i -H "Authorization: Bearer $ACCESS_TOKEN" http://localhost:8000/api/meTo use it for all DRF views, put "mysite.api_auth.KeycloakJWTAuthentication" in DEFAULT_AUTHENTICATION_CLASSES under the REST_FRAMEWORK setting instead of setting authentication_classes per view.
Log out
Django's logout alone ends only the Django session. The Keycloak session stays, so the next Log in signs the user straight back in. The settings above make the library's logout view send the browser to Keycloak's end-session endpoint as well:
OIDC_STORE_ID_TOKEN = Truekeeps the ID token in the Django session asoidc_id_token.OIDC_OP_LOGOUT_URL_METHODnames a function that returns the URL to redirect to.
from urllib.parse import urlencode
from django.conf import settings
def keycloak_logout_url(request):
# mozilla-django-oidc calls this before it ends the Django session,
# so the stored ID token is still available here.
params = {
"client_id": settings.OIDC_RP_CLIENT_ID,
"post_logout_redirect_uri": request.build_absolute_uri(settings.LOGOUT_REDIRECT_URL),
}
id_token = request.session.get("oidc_id_token")
if id_token:
params["id_token_hint"] = id_token
return f"{settings.KEYCLOAK_LOGOUT_ENDPOINT}?{urlencode(params)}"The result looks like https://auth.example.com/realms/acme/protocol/openid-connect/logout?client_id=my-app&post_logout_redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&id_token_hint=.... Keycloak ends its session and returns the browser to http://localhost:8000/, which must be listed in Valid post logout redirect URIs. With id_token_hint, Keycloak does not ask the user to confirm. The logout URL builder builds and checks the same URL.
The logout view accepts POST only, which is why the template uses a form with {% csrf_token %}.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Keycloak shows Invalid parameter: redirect_uri | The callback URL Django sends is not in Valid redirect URIs. It is built from the request, so 127.0.0.1 and localhost differ, and so do http and https. | Add the exact URL, with the trailing slash. Compare both with the redirect URI matcher. |
The callback uses http:// in production | Django runs behind a TLS proxy and does not know the request was HTTPS. | Set SECURE_PROXY_SSL_HEADER for your proxy. |
Login returns to the home page, still logged out; the mozilla_django_oidc log says Claims verification failed | The Keycloak user has no email address. | Set the user's email, or override verify_claims and the user lookup in a subclass of the backend. |
ImproperlyConfigured: RS256 alg requires OIDC_RP_IDP_SIGN_KEY or OIDC_OP_JWKS_ENDPOINT to be configured. | OIDC_OP_JWKS_ENDPOINT is missing. | Set it to the realm's /protocol/openid-connect/certs URL. |
| Keycloak shows Invalid redirect uri after logout | post_logout_redirect_uri is not in Valid post logout redirect URIs. | Add http://localhost:8000/ (or your production URL) exactly. |
405 Method Not Allowed on /oidc/logout/ | The logout was a link (GET). | Use a POST form, as in the template. |
401 Invalid token: Audience doesn't match | The access token has no my-api in aud. | Add the Audience mapper. Check the token with the JWT decoder. |
401 Invalid token: Invalid issuer | OIDC_ISSUER differs from the token's iss: another hostname, realm or scheme. | Copy issuer from the discovery document, for example with the OIDC discovery viewer. |
401 Invalid token: Signature has expired | Keycloak access tokens live 5 minutes by default. | The caller refreshes the token and retries. |
401 Invalid token: Unable to find a signing key that matches | The token comes from another realm or server, or its kid is not in the JWKS. | Compare the token's kid with the realm's keys using the JWT kid matcher. |
FAQ
How are Django users matched to Keycloak users?
By email, by default. The Django username is a hash of the email. If users can change their email in Keycloak, subclass OIDCAuthenticationBackend and override filter_users_by_claims and create_user to match on the sub claim instead, as the mozilla-django-oidc docs describe.
Can I use PKCE as well?
Yes. Set OIDC_USE_PKCE = True. mozilla-django-oidc then sends an S256 code challenge, which Keycloak accepts without extra client settings.
Why not mozilla-django-oidc's DRF class?
It calls Keycloak's userinfo endpoint for every API request and does not check the audience. Local validation with PyJWT is faster, works when Keycloak is briefly unreachable once the keys are cached, and accepts only tokens meant for your API.
Do I need to ask you to open an outgoing connection?
No. Every call in this guide goes from your app to Keycloak: token, userinfo and JWKS. Logout is a browser redirect, so Keycloak never calls your app.
Sources
- mozilla-django-oidc installation
- mozilla-django-oidc DRF integration
- mozilla-django-oidc on PyPI
- PyJWT usage: PyJWKClient
- Django REST Framework authentication
- Django 6.1 documentation
- Keycloak OIDC endpoints
- Keycloak Server Administration Guide: audience, mappers, logout
- OpenID Connect RP-Initiated Logout 1.0
Add Keycloak login to an ASP.NET Core app
Sign users in to an ASP.NET Core minimal API app with Keycloak through the OpenID Connect handler, protect an API with JwtBearer, and log out of Keycloak.
Add Keycloak login to a FastAPI app
Validate Keycloak access tokens in FastAPI with PyJWT and JWKS, add browser login with Authlib, and log users out of Keycloak.