| 1 | from __future__ import annotations |
| 2 | |
| 3 | import datetime |
| 4 | import uuid |
| 5 | from typing import Any |
| 6 | |
| 7 | import jwt |
| 8 | |
| 9 | |
| 10 | def create_client_assertion_jwt( |
| 11 | domain: str, |
| 12 | client_id: str, |
| 13 | client_assertion_signing_key: str, |
| 14 | client_assertion_signing_alg: str | None, |
| 15 | ) -> str: |
| 16 | """Creates a JWT for the client_assertion field. |
| 17 | |
| 18 | Args: |
| 19 | domain (str): The domain of your Auth0 tenant |
| 20 | client_id (str): Your application's client ID |
| 21 | client_assertion_signing_key (str): Private key used to sign the client assertion JWT |
| 22 | client_assertion_signing_alg (str, optional): Algorithm used to sign the client assertion JWT (defaults to 'RS256') |
| 23 | |
| 24 | Returns: |
| 25 | A JWT signed with the `client_assertion_signing_key`. |
| 26 | """ |
| 27 | client_assertion_signing_alg = client_assertion_signing_alg or "RS256" |
| 28 | now = datetime.datetime.utcnow() |
| 29 | return jwt.encode( |
| 30 | { |
| 31 | "iss": client_id, |
| 32 | "sub": client_id, |
| 33 | "aud": f"https://{domain}/", |
| 34 | "iat": now, |
| 35 | "exp": now + datetime.timedelta(seconds=180), |
| 36 | "jti": str(uuid.uuid4()), |
| 37 | }, |
| 38 | client_assertion_signing_key, |
| 39 | client_assertion_signing_alg, |
| 40 | ) |
| 41 | |
| 42 | |
| 43 | def add_client_authentication( |
| 44 | payload: dict[str, Any], |
| 45 | domain: str, |
| 46 | client_id: str, |
| 47 | client_secret: str | None, |
| 48 | client_assertion_signing_key: str | None, |
| 49 | client_assertion_signing_alg: str | None, |
| 50 | ) -> dict[str, Any]: |
| 51 | """Adds the client_assertion or client_secret fields to authenticate a payload. |
| 52 | |
| 53 | Args: |
| 54 | payload (dict): The POST payload that needs additional fields to be authenticated. |
| 55 | domain (str): The domain of your Auth0 tenant |
| 56 | client_id (str): Your application's client ID |
| 57 | client_secret (str, optional): Your application's client secret |
| 58 | client_assertion_signing_key (str, optional): Private key used to sign the client assertion JWT |
| 59 | client_assertion_signing_alg (str, optional): Algorithm used to sign the client assertion JWT (defaults to 'RS256') |
| 60 | |
| 61 | Returns: |
| 62 | A copy of the payload with client authentication fields added. |
| 63 | """ |
| 64 | |
| 65 | authenticated_payload = payload.copy() |
| 66 | if client_assertion_signing_key: |
| 67 | authenticated_payload["client_assertion"] = create_client_assertion_jwt( |
| 68 | domain, |
| 69 | client_id, |
| 70 | client_assertion_signing_key, |
| 71 | client_assertion_signing_alg, |
| 72 | ) |
| 73 | authenticated_payload[ |
| 74 | "client_assertion_type" |
| 75 | ] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" |
| 76 | elif client_secret: |
| 77 | authenticated_payload["client_secret"] = client_secret |
| 78 | return authenticated_payload |