メインコンテンツにスキップ

Kubernetes

Kubernetesドキュメントによると、KubernetesのAPIサーバーはOpenID Connect(OIDC)を使用して認証できます。 この記事では、Casdoorを使用してKubernetesで認証を設定する方法について説明します。

環境要件

Prerequisites:

  • Kubernetesクラスター。
  • このようなデモウェブサイトのCasdoorアプリケーション。
  • kubectlコマンドツール(オプション)。

Kubernetesのoidc-issuer-urlは、https://プレフィックスを使用するURLのみを受け入れます。 したがって、CasdoorアプリケーションはHTTPSウェブサイトにデプロイされるべきです。

ステップ1:認証用のCasdoorアプリとユーザーアカウントを作成する

In Casdoor add an application (e.g. Kubernetes). Note Name, Organization, Client ID, and Client secret. Enable the grant types the cluster will use.

Casdoorでアプリケーションを作成する グラントタイプ

Add a user; set Organization and Signup application to the application you created.

Casdoorにユーザーを追加する

ステップ2:OIDC認証を使用してKubernetes APIサーバーを設定する

To enable the OIDC plugin, set the following flags on the API server:

  • --oidc-issuer-url:APIサーバーが公開署名キーを発見することを許可するプロバイダーのURL。
  • --oidc-client-id:すべてのトークンが発行される必要があるクライアントID。

この記事では、デモンストレーションのためにminikubeを使用しています。 Configure the OIDC plugin for the minikube API server using the following command at startup:

minikube start --extra-config=apiserver.oidc-issuer-url=https://demo.casdoor.com --extra-config=apiserver.oidc-client-id=294b09fbc17f95daf2fe

ステップ3:OIDC認証をテストする

認証情報を取得する

kubectlにフロントエンドがないため、CasdoorサーバーにPOSTリクエストを送信することで認証を行うことができます。 以下は、CasdoorサーバーにPOSTリクエストを送信し、id_tokenrefresh_tokenを取得するPythonのコードです:

import requests
import json

url = "https://demo.casdoor.com/api/login/oauth/access_token"
payload = json.dumps({
"grant_type": "password",
"client_id": "Kubernetes",
"client_secret": "72c65c3912aec24a9f3ec41b65a7577114ed2bae",
"username": "user_3u94sf",
"password": "123456"
})
response = requests.request("POST", url, data=payload)

print(response.text)

このコードを実行した後、以下のようなレスポンスを受け取るはずです:

{
"access_token": "xxx",
"id_token": "yyy",
"refresh_token": "zzz",
"token_type": "Bearer",
"expires_in": 72000,
"scope": ""
}

Use the obtained id_token to authenticate with the Kubernetes API server.

HTTPリクエストベースの認証

リクエストヘッダーにトークンを追加します。

curl https://www.xxx.com -k -H "Authorization: Bearer $(id_token)"
  • https://www.xxx.comはKubernetes APIサーバーのデプロイメントアドレスです。

Kubectlクライアントベースの認証

設定ファイルメソッド

~/.kube/configファイルに以下の設定を書き込みます。 上記の設定ファイル内の各設定項目を、以前に取得した値に置き換える必要があります。

users:
- name: minikube
user:
auth-provider:
config:
client-id: Kubernetes
client-secret: 72c65c3912aec24a9f3ec41b65a7577114ed2bae
id-token: $(id_token)
idp-issuer-url: https://demo.casdoor.com
refresh-token: $(refresh_token)
name: oidc

Access the API server with kubectl. テストコマンドを実行してみてください。

kubectl cluster-info

コマンドライン引数メソッド

Alternatively, pass the id_token in kubectl command-line parameters.

kubectl --token=$(id_token) cluster-info