swh.auth.django.backends module

class swh.auth.django.backends.OIDCAuthorizationCodePKCEBackend[source]

Bases: object

Django authentication backend using Keycloak OpenID Connect authorization code flow with PKCE (“Proof Key for Code Exchange”).

To use that backend globally in your django application, proceed as follow:

  • add "swh.auth.django.backends.OIDCAuthorizationCodePKCEBackend" to the AUTHENTICATION_BACKENDS django setting

  • configure Keycloak URL, realm and client by adding SWH_AUTH_SERVER_URL, SWH_AUTH_REALM_NAME and SWH_AUTH_CLIENT_ID in django settings

  • add swh.auth.django.views.urlpatterns to your django application URLs

  • add an HTML link targeting the "oidc-login" django view in your application views

  • once a user is logged in, add an HTML link targeting the "oidc-logout" django view in your application views (a next_path query parameter can be used to redirect to a view of choice once the user is logged out)

authenticate(request: django.http.request.HttpRequest, code: str, code_verifier: str, redirect_uri: str) Optional[swh.auth.django.models.OIDCUser][source]
get_user(user_id: int) Optional[swh.auth.django.models.OIDCUser][source]
class swh.auth.django.backends.OIDCBearerTokenAuthentication[source]

Bases: rest_framework.authentication.BaseAuthentication

Django REST Framework authentication backend using bearer tokens for Keycloak OpenID Connect.

It enables to authenticate a Web API user by sending a long-lived OpenID Connect refresh token in HTTP Authorization headers. Long lived refresh tokens can be generated by opening an OpenID Connect session with the following scope: openid offline_access.

To use that backend globally in your DRF application, proceed as follow:

  • add "swh.auth.django.backends.OIDCBearerTokenAuthentication" to the REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"] django setting.

  • configure Keycloak URL, realm and client by adding SWH_AUTH_SERVER_URL, SWH_AUTH_REALM_NAME and SWH_AUTH_CLIENT_ID in django settings

Users will then be able to perform authenticated Web API calls by sending their refresh token in HTTP Authorization headers, for instance: curl -H "Authorization: Bearer ${TOKEN}" https://....

authenticate(request)[source]

Authenticate the request and return a two-tuple of (user, token).