MESH example Python code does not work

The code @ Message Exchange for Social Care and Health (MESH) API - NHS Digital isn’t valid python3 (that’s not how you do an import) and contains typos, and no actual output.

Here is a corrected version. Save it to a file and run it.
Expected output:

NHSMESH XXX5555:6f732ccc-8c6f-4c9b-a22d-2f42978550ad:0:202308251028:026e8d63f07be7ad3606e4c5262b3c954dfd6b7697cbf2e34ae3646862cd3d0f

""" Python code to generate a valid authorization header. """
import hmac
import uuid
import datetime
import hashlib

AUTHSCHEMANAME = "NHSMESH " # Note: Space at the end of the schema.
SHARED_KEY = "tbc" # Note: Don't hard code your passwords in a real implementation.

def build_auth_header(mailbox_id: str, password: str = "password", nonce: str = None, nonce_count: int = 0):
  """ Generate MESH Authorization header for mailboxid. """
  #Generate a GUID if required.
  if not nonce:
    nonce = str(uuid.uuid4())
  #Current time formatted as yyyyMMddHHmm
  #for example, 4th May 2020 13:05 would be 202005041305
  timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M")

  #for example, NHSMESH AMP01HC001:bd0e2bd5-218e-41d0-83a9-73fdec414803:0:202005041305
  hmac_msg = mailbox_id + ":" + nonce + ":" + str(nonce_count) + ":" + password + ":" + timestamp

  #HMAC is a standard crypto hash method built in the python standard library.
  hash_code = hmac.HMAC(SHARED_KEY.encode(), hmac_msg.encode(), "sha256").hexdigest()
  return (
    AUTHSCHEMANAME # Note: No colon between 1st and 2nd elements.
    + mailbox_id + ":"
    + nonce + ":"
    + str(nonce_count) + ":"
    + timestamp+ ":"
    + hash_code
  )

print ( build_auth_header( "XXX5555","klshdf09w734","6f732ccc-8c6f-4c9b-a22d-2f42978550ad" ) )
1 Like

Hello tc1
Great catch. I have passed this information on to itoc.supportdesk@nhs.net and ssd.nationalservicedesk@nhs.net for their attention.

Could you let them know the curl example on Message Exchange for Social Care and Health (MESH) API - NHS Digital is also using GET instead of POST ?

Hello tc1, Will do.

Thanks !

( post must be at least 20 characters )

addressed as part of mesh-1629: fix auth pseudocode and add request body / response schema… by matt-mercer · Pull Request #119 · NHSDigital/mesh-api-specification · GitHub