|
| 1 | +import uuid |
| 2 | +import argparse |
| 3 | +from time import time |
| 4 | +import requests |
| 5 | +import jwt # https://github.com/jpadilla/pyjwt |
| 6 | + |
| 7 | +ENV_TOKEN_URLS = { |
| 8 | + "int": "https://int.api.service.nhs.uk/oauth2/token", |
| 9 | + "internal-dev": "https://internal-dev.api.service.nhs.uk/oauth2-mock/token", |
| 10 | + "prod": "https://api.service.nhs.uk/oauth2/token", |
| 11 | + "ref": "https://ref.api.service.nhs.uk/oauth2/token", |
| 12 | +} |
| 13 | + |
| 14 | +def main(): |
| 15 | + ap = argparse.ArgumentParser(description="Fetch NHS access token using a signed client assertion (JWT).") |
| 16 | + ap.add_argument("--kid", required=True, |
| 17 | + help="Base name used for both the private key file (<id>.pem) and the JWT header kid.") |
| 18 | + ap.add_argument("--env", choices=ENV_TOKEN_URLS.keys(), required=True, |
| 19 | + help="Environment to hit: int, internal-dev, or prod.") |
| 20 | + ap.add_argument("--appid", help="Apigee Application ID (used for both sub and iss).") |
| 21 | + args = ap.parse_args() |
| 22 | + |
| 23 | + kid = args.kid |
| 24 | + private_key_file = f"{kid}.pem" |
| 25 | + token_url = ENV_TOKEN_URLS[args.env] |
| 26 | + |
| 27 | + with open(private_key_file, "r") as f: |
| 28 | + private_key = f.read() |
| 29 | + |
| 30 | + claims = { |
| 31 | + "sub": args.appid, |
| 32 | + "iss": args.appid, |
| 33 | + "jti": str(uuid.uuid4()), |
| 34 | + "aud": token_url, |
| 35 | + "exp": int(time()) + 300, # 5mins in the future |
| 36 | + } |
| 37 | + |
| 38 | + additional_headers = {"kid": kid} |
| 39 | + |
| 40 | + signed_jwt = jwt.encode( |
| 41 | + claims, private_key, algorithm="RS512", headers=additional_headers |
| 42 | + ) |
| 43 | +# ----- 2) Exchange JWT for an access token ----- |
| 44 | + form = { |
| 45 | + "grant_type": "client_credentials", |
| 46 | + "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", |
| 47 | + "client_assertion": signed_jwt, |
| 48 | + } |
| 49 | + |
| 50 | + resp = requests.post( |
| 51 | + token_url, |
| 52 | + headers={"content-type": "application/x-www-form-urlencoded"}, |
| 53 | + data=form, |
| 54 | + timeout=30, |
| 55 | + ) |
| 56 | + |
| 57 | + # Raise for non-2xx responses, then print the token payload |
| 58 | + resp.raise_for_status() |
| 59 | + token_payload = resp.json() |
| 60 | + |
| 61 | + print("access_token:", token_payload.get("access_token")) |
| 62 | + print("expires_in:", token_payload.get("expires_in")) |
| 63 | + print("token_type:", token_payload.get("token_type")) |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + main() |
0 commit comments