4.2. REST API を使用した認証

API 呼び出しには、API トークンによる認証が必要です。変数名として API_TOKEN を使用すると仮定すると、API 呼び出しに -H "Authorization: Bearer ${API_TOKEN}" を追加して、REST API で認証します。

注記

API トークンは 15 分後に期限切れになります。

前提条件

  • (オプション) OpenShift Cluster Manager (ocm) CLI ツールがインストールされている。

手順

  1. OFFLINE_TOKEN を使用して API_TOKEN 変数を設定し、ユーザーを検証します。

    1. (オプション) コマンドラインターミナルで、次のコマンドを実行します。

      $ export API_TOKEN=$( \
        curl \
        --silent \
        --header "Accept: application/json" \
        --header "Content-Type: application/x-www-form-urlencoded" \
        --data-urlencode "grant_type=refresh_token" \
        --data-urlencode "client_id=cloud-services" \
        --data-urlencode "refresh_token=${OFFLINE_TOKEN}" \
        "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token" \
        | jq --raw-output ".access_token" \
      )
    2. (オプション) コマンドライン端末で、ocm クライアントにログインします。

      $ ocm login --token="${OFFLINE_TOKEN}"

      次に、API トークンを生成します。

      $ export API_TOKEN=$(ocm token)
  1. トークン生成方法の 1 つのパスにスクリプトを作成します。以下に例を示します。

    $ vim ~/.local/bin/refresh-token
    export API_TOKEN=$( \
      curl \
      --silent \
      --header "Accept: application/json" \
      --header "Content-Type: application/x-www-form-urlencoded" \
      --data-urlencode "grant_type=refresh_token" \
      --data-urlencode "client_id=cloud-services" \
      --data-urlencode "refresh_token=${OFFLINE_TOKEN}" \
      "https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token" \
      | jq --raw-output ".access_token" \
    )

    次に、ファイルを保存します。

  2. ファイルモードを変更して実行可能にします。

    $ chmod +x ~/.local/bin/refresh-token
  3. API トークンを更新します。

    $ source refresh-token
  4. 次のコマンドを実行して、API にアクセスできることを確認します。

    $ curl -s https://api.openshift.com/api/assisted-install/v2/component-versions -H "Authorization: Bearer ${API_TOKEN}" | jq

    出力例

    {
      "release_tag": "v2.11.3",
      "versions": {
        "assisted-installer": "registry.redhat.io/rhai-tech-preview/assisted-installer-rhel8:v1.0.0-211",
        "assisted-installer-controller": "registry.redhat.io/rhai-tech-preview/assisted-installer-reporter-rhel8:v1.0.0-266",
        "assisted-installer-service": "quay.io/app-sre/assisted-service:78d113a",
        "discovery-agent": "registry.redhat.io/rhai-tech-preview/assisted-installer-agent-rhel8:v1.0.0-195"
      }
    }