Search code examples
pythonsecurityibm-cloud

IBM Cloud: API function to find account ID for existing IAM access token?


In my script I have an IBM Cloud IAM bearer token (access token). Some API functions require to pass in the account ID. Which API functions would allow me to retrieve the related account ID? I know that I could base64 decode the access token, but...


Solution

  • There is an API function to retrieve the list of accounts and only needs a bearer token:

    curl -X GET "https://accounts.cloud.ibm.com/v1/accounts" 
    -H "Authorization: $IBMCLOUD_TOKEN" -H 'Content-Type: application/json'
    

    The API can be seen in use with trace enabled during login using the CLI. The service is described as Account Management Service in the CLI docs.

    I resorted to just decoding the bearer token:

    # use split and base64 to get to the content of the IAM token
    def extractAccount(iam_token):
        data = iam_token.split('.')
        padded = data[1] + "="*divmod(len(data[1]),4)[1]
        jsondata = json.loads(base64.urlsafe_b64decode(padded))
        return jsondata
    

    The account ID can then be retrieved by accessing the related field in the token payload:

    token_data=extractAccount(iam_token)
    account_id=token_data["account"]["bss"]