|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from datetime import timedelta |
| 4 | + |
| 5 | +import requests |
| 6 | +from django.contrib.auth.signals import user_logged_out |
| 7 | +from django.dispatch import receiver |
| 8 | +from django.utils import timezone |
| 9 | +from jwcrypto import jwt |
| 10 | + |
| 11 | +from .exceptions import BackchannelLogoutRequestError |
| 12 | +from .models import AbstractApplication, get_id_token_model |
| 13 | +from .settings import oauth2_settings |
| 14 | + |
| 15 | + |
| 16 | +IDToken = get_id_token_model() |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def send_backchannel_logout_request(id_token, *args, **kwargs): |
| 22 | + """ |
| 23 | + Send a logout token to the applications backchannel logout uri |
| 24 | + """ |
| 25 | + |
| 26 | + ttl = kwargs.get("ttl") or timedelta(minutes=10) |
| 27 | + |
| 28 | + try: |
| 29 | + assert oauth2_settings.OIDC_BACKCHANNEL_LOGOUT_ENABLED, "Backchannel logout not enabled" |
| 30 | + assert id_token.application.algorithm != AbstractApplication.NO_ALGORITHM, ( |
| 31 | + "Application must provide signing algorithm" |
| 32 | + ) |
| 33 | + assert id_token.application.backchannel_logout_uri is not None, ( |
| 34 | + "URL for backchannel logout not provided by client" |
| 35 | + ) |
| 36 | + |
| 37 | + issued_at = timezone.now() |
| 38 | + expiration_date = issued_at + ttl |
| 39 | + |
| 40 | + claims = { |
| 41 | + "iss": oauth2_settings.OIDC_ISS_ENDPOINT, |
| 42 | + "sub": str(id_token.user.id), |
| 43 | + "aud": str(id_token.application.client_id), |
| 44 | + "iat": int(issued_at.timestamp()), |
| 45 | + "exp": int(expiration_date.timestamp()), |
| 46 | + "jti": id_token.jti, |
| 47 | + "events": {"http://schemas.openid.net/event/backchannel-logout": {}}, |
| 48 | + } |
| 49 | + |
| 50 | + # Standard JWT header |
| 51 | + header = {"typ": "logout+jwt", "alg": id_token.application.algorithm} |
| 52 | + |
| 53 | + # RS256 consumers expect a kid in the header for verifying the token |
| 54 | + if id_token.application.algorithm == AbstractApplication.RS256_ALGORITHM: |
| 55 | + header["kid"] = id_token.application.jwk_key.thumbprint() |
| 56 | + |
| 57 | + token = jwt.JWT( |
| 58 | + header=json.dumps(header, default=str), |
| 59 | + claims=json.dumps(claims, default=str), |
| 60 | + ) |
| 61 | + |
| 62 | + token.make_signed_token(id_token.application.jwk_key) |
| 63 | + |
| 64 | + headers = {"Content-Type": "application/x-www-form-urlencoded"} |
| 65 | + data = {"logout_token": token.serialize()} |
| 66 | + response = requests.post(id_token.application.backchannel_logout_uri, headers=headers, data=data) |
| 67 | + response.raise_for_status() |
| 68 | + except (AssertionError, requests.RequestException) as exc: |
| 69 | + raise BackchannelLogoutRequestError(str(exc)) |
| 70 | + |
| 71 | + |
| 72 | +@receiver(user_logged_out) |
| 73 | +def on_user_logged_out_maybe_send_backchannel_logout(sender, **kwargs): |
| 74 | + handler = oauth2_settings.OIDC_BACKCHANNEL_LOGOUT_HANDLER |
| 75 | + if not oauth2_settings.OIDC_BACKCHANNEL_LOGOUT_ENABLED or not callable(handler): |
| 76 | + return |
| 77 | + |
| 78 | + user = kwargs["user"] |
| 79 | + id_tokens = IDToken.objects.filter(application__backchannel_logout_uri__isnull=False, user=user) |
| 80 | + for id_token in id_tokens: |
| 81 | + try: |
| 82 | + handler(id_token=id_token) |
| 83 | + except BackchannelLogoutRequestError as exc: |
| 84 | + logger.warn(str(exc)) |
0 commit comments