IBM Cloud Docs
Retrieving IAM access tokens

Retrieving IAM access tokens

To use the Activity Tracking API, you must use an IBM Cloud® Identity and Access Management (IAM) access token. Each token is valid only for one hour, and after a token expires, you must request a new one if you want to continue using the API.

Retrieving an access token for the current session by using the IBM Cloud CLI

You can use the IBM Cloud CLI to generate your IAM access token.

Complete the following steps to generate an access token for the current session:

  1. Log in to IBM Cloud with the IBM Cloud CLI.

    ibmcloud login
    

    If the login fails, run the ibmcloud login --sso command to try again. The --sso parameter is required when you log in with a federated ID. If this option is used, go to the link listed in the CLI output to generate a one-time passcode.

  2. Run the following command to retrieve your Cloud IAM access token.

    ibmcloud iam oauth-tokens | grep IAM | cut -d \: -f 2 | sed 's/^ *//'
    

    The following truncated example shows a retrieved IAM token.

    IAM token:  Bearer eyJraWQiOiIyM...
    

Retrieving an access token by using an API key and the IBM Cloud CLI

You can also retrieve your access token programmatically by creating a service ID API key for your application, and then exchanging your API key for an IBM Cloud IAM token.

  1. Log in to IBM Cloud with the IBM Cloud CLI.

    ibmcloud login -a cloud.ibm.com [--apikey KEY | @KEY_FILE]
    

    Where KEY | @KEY_FILE is the API key that you want to use to get the access token.

  2. Run the following command to get an IAM access token.

    ibmcloud iam oauth-tokens | grep IAM | cut -d \: -f 2 | sed 's/^ *//'
    

    The following truncated example shows a retrieved IAM token.

    IAM token:  Bearer eyJraWQiOiIyM...
    

Retrieving an access token by using an API key in a cURL request

Run the following cURL command to call the IAM Identity Services API to retrieve your access token:

curl -X POST \
    'https://iam.cloud.ibm.com/identity/token' \
    -H 'content-type: application/x-www-form-urlencoded' \
    -H 'accept: application/json' \
    -d 'grant_type=urn%3Aibm%3Aparams%3Aoauth%3Agrant-type%3Aapikey&apikey=<API_KEY>' > token.json

Replace <API_KEY> with your API key.

The following truncated example shows the contents of the token.json file:

{
    "access_token": "b3VyIGZhdGhlc...",
    "expiration": 1512161390,
    "expires_in": 3600,
    "refresh_token": "dGhpcyBjb250a...",
    "token_type": "Bearer"
}

Use the full access_token value, prefixed by the Bearer token type.