使用 Azure CLI 整合 Azure Active Directory 與 Azure Kubernetes ServiceIntegrate Azure Active Directory with Azure Kubernetes Service using the Azure CLI

Azure Kubernetes Service (AKS) 可以設定為使用 Azure Active Directory (AD) 進行使用者驗證。Azure Kubernetes Service (AKS) can be configured to use Azure Active Directory (AD) for user authentication. 在此設定中, 您可以使用 Azure AD 驗證權杖來登入 AKS 叢集。In this configuration, you can log into an AKS cluster using an Azure AD authentication token. 叢集操作員也可以根據使用者的身分識別或目錄群組成員資格, 設定 Kubernetes 角色型存取控制 (RBAC)。Cluster operators can also configure Kubernetes role-based access control (RBAC) based on a user's identity or directory group membership.

本文說明如何建立必要的 Azure AD 元件, 然後部署已啟用 Azure AD 的叢集, 並在 AKS 叢集中建立基本的 RBAC 角色。This article shows you how to create the required Azure AD components, then deploy an Azure AD-enabled cluster and create a basic RBAC role in the AKS cluster. 您也可以使用 Azure 入口網站來完成這些步驟You can also complete these steps using the Azure portal.

如需本文中使用的完整範例腳本, 請參閱Azure CLI 範例-AKS 與 Azure AD 整合For the complete sample script used in this article, see Azure CLI samples - AKS integration with Azure AD.

套用下列限制:The following limitations apply:

  • 只有建立啟用 RBAC 功能的新叢集時,才能啟用 Azure AD。Azure AD can only be enabled when you create a new, RBAC-enabled cluster. 您無法在現有的 AKS 叢集上啟用 Azure AD。You can't enable Azure AD on an existing AKS cluster.

開始之前Before you begin

您需要安裝並設定 Azure CLI 版本2.0.61 或更新版本。You need the Azure CLI version 2.0.61 or later installed and configured. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

為求一致, 並協助執行本文中的命令, 請為您想要的 AKS 叢集名稱建立一個變數。For consistency and to help run the commands in this article, create a variable for your desired AKS cluster name. 下列範例會使用名稱myakscluster:The following example uses the name myakscluster:

aksname="myakscluster"

Azure AD 驗證總覽Azure AD authentication overview

透過 OpenID Connect 對 AKS 叢集提供 Azure AD 驗證。Azure AD authentication is provided to AKS clusters with OpenID Connect. OpenID Connect 是以 OAuth 2.0 通訊協定為建置基礎的身分識別層。OpenID Connect is an identity layer built on top of the OAuth 2.0 protocol. 如需 OpenID Connect 的詳細資訊, 請參閱OPEN ID connect 檔For more information on OpenID Connect, see the Open ID connect documentation.

從 Kubernetes 叢集內部,Webhook 權杖驗證用來確認驗證權杖。From inside of the Kubernetes cluster, Webhook Token Authentication is used to verify authentication tokens. Webhook 權杖驗證已設定並當作 AKS 叢集的一部分管理。Webhook token authentication is configured and managed as part of the AKS cluster. 如需 Webhook 權杖驗證的詳細資訊, 請參閱webhook 驗證檔For more information on Webhook token authentication, see the webhook authentication documentation.

注意

設定 Azure AD 以進行 AKS 驗證時,會設定兩個 Azure AD 應用程式。When configuring Azure AD for AKS authentication, two Azure AD applications are configured. 這項作業必須由 Azure 租用戶系統管理員完成。This operation must be completed by an Azure tenant administrator.

建立 Azure AD 伺服器元件Create Azure AD server component

若要與 AKS 整合, 您可以建立並使用作為身分識別要求端點的 Azure AD 應用程式。To integrate with AKS, you create and use an Azure AD application that acts as an endpoint for the identity requests. 您需要的第一個 Azure AD 應用程式會取得使用者 Azure AD 群組成員資格。The first Azure AD application you need gets Azure AD group membership for a user.

使用az ad app create命令來建立伺服器應用程式元件, 然後使用az ad app update命令來更新群組成員資格宣告。Create the server application component using the az ad app create command, then update the group membership claims using the az ad app update command. 下列範例會使用 [在您開始前] 區段中定義的aksname變數, 並建立變數The following example uses the aksname variable defined in the Before you begin section, and creates a variable

# Create the Azure AD application
serverApplicationId=$(az ad app create \
    --display-name "${aksname}Server" \
    --identifier-uris "https://${aksname}Server" \
    --query appId -o tsv)

# Update the application group memebership claims
az ad app update --id $serverApplicationId --set groupMembershipClaims=All

現在, 使用az ad sp create命令來建立伺服器應用程式的服務主體。Now create a service principal for the server app using the az ad sp create command. 此服務主體是用來在 Azure 平臺內自行驗證。This service principal is used to authenticate itself within the Azure platform. 然後, 使用az ad sp credential reset命令取得服務主體秘密, 並將指派給名為serverApplicationSecret的變數, 以用於下列其中一個步驟:Then, get the service principal secret using the az ad sp credential reset command and assign to the variable named serverApplicationSecret for use in one of the following steps:

# Create a service principal for the Azure AD application
az ad sp create --id $serverApplicationId

# Get the service principal secret
serverApplicationSecret=$(az ad sp credential reset \
    --name $serverApplicationId \
    --credential-description "AKSPassword" \
    --query password -o tsv)

Azure AD 需要執行下列動作的許可權:The Azure AD needs permissions to perform the following actions:

  • 讀取目錄資料Read directory data
  • 登入及讀取使用者個人檔案Sign in and read user profile

使用az ad app 許可權 add命令來指派這些許可權:Assign these permissions using the az ad app permission add command:

az ad app permission add \
    --id $serverApplicationId \
    --api 00000003-0000-0000-c000-000000000000 \
    --api-permissions e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope 06da0dbc-49e2-44d2-8312-53f166ab848a=Scope 7ab1d382-f21e-4acd-a863-ba3e13f7da61=Role

最後, 使用az ad app 許可權 grant命令, 授與在上一個步驟中為伺服器應用程式指派的許可權。Finally, grant the permissions assigned in the previous step for the server application using the az ad app permission grant command. 如果目前的帳戶不是租使用者系統管理員, 則此步驟會失敗。您也需要新增 Azure AD 應用程式的許可權, 以要求可能需要使用az AD app 許可權系統管理員同意來進行系統管理同意的資訊:This step fails if the current account is not a tenant admin. You also need to add permissions for Azure AD application to request information that may otherwise require administrative consent using the az ad app permission admin-consent:

az ad app permission grant --id $serverApplicationId --api 00000003-0000-0000-c000-000000000000
az ad app permission admin-consent --id  $serverApplicationId

建立 Azure AD 用戶端元件Create Azure AD client component

當使用者使用 Kubernetes CLI (kubectl) 登入 AKS 叢集時, 會使用第二個 Azure AD 應用程式。The second Azure AD application is used when a user logs to the AKS cluster with the Kubernetes CLI (kubectl). 此用戶端應用程式會接受來自使用者的驗證要求, 並驗證其認證和許可權。This client application takes the authentication request from the user and verifies their credentials and permissions. 使用az AD app create命令, 建立用戶端元件的 Azure AD 應用程式:Create the Azure AD app for the client component using the az ad app create command:

clientApplicationId=$(az ad app create \
    --display-name "${aksname}Client" \
    --native-app \
    --reply-urls "https://${aksname}Client" \
    --query appId -o tsv)

使用az ad sp create命令來建立用戶端應用程式的服務主體:Create a service principal for the client application using the az ad sp create command:

az ad sp create --id $clientApplicationId

取得伺服器應用程式的 oAuth2 識別碼, 以允許使用az ad app show命令在兩個應用程式元件之間進行驗證流程。Get the oAuth2 ID for the server app to allow the authentication flow between the two app components using the az ad app show command. 在下一個步驟中會使用此 oAuth2 識別碼。This oAuth2 ID is used in the next step.

oAuthPermissionId=$(az ad app show --id $serverApplicationId --query "oauth2Permissions[0].id" -o tsv)

使用az ad app 許可權 add命令, 新增用戶端應用程式和伺服器應用程式元件的許可權, 以使用 oAuth2 通訊流程。Add the permissions for the client application and server application components to use the oAuth2 communication flow using the az ad app permission add command. 然後, 使用az ad app 許可權 grant命令, 授與用戶端應用程式與伺服器應用程式通訊的許可權:Then, grant permissions for the client application to communication with the server application using the az ad app permission grant command:

az ad app permission add --id $clientApplicationId --api $serverApplicationId --api-permissions $oAuthPermissionId=Scope
az ad app permission grant --id $clientApplicationId --api $serverApplicationId

部署叢集Deploy the cluster

建立兩個 Azure AD 應用程式後, 現在建立 AKS 叢集本身。With the two Azure AD applications created, now create the AKS cluster itself. 首先, 使用az group create命令來建立資源群組。First, create a resource group using the az group create command. 下列範例會在EastUS區域中建立資源群組:The following example creates the resource group in the EastUS region:

建立叢集的資源群組:Create a resource group for the cluster:

az group create --name myResourceGroup --location EastUS

使用az account show命令取得 Azure 訂用帳戶的租使用者識別碼。Get the tenant ID of your Azure subscription using the az account show command. 然後, 使用az AKS create命令來建立 AKS 叢集。Then, create the AKS cluster using the az aks create command. 建立 AKS 叢集的命令會提供伺服器和用戶端應用程式識別碼、伺服器應用程式服務主體密碼和您的租使用者識別碼:The command to create the AKS cluster provides the server and client application IDs, the server application service principal secret, and your tenant ID:

tenantId=$(az account show --query tenantId -o tsv)

az aks create \
    --resource-group myResourceGroup \
    --name $aksname \
    --node-count 1 \
    --generate-ssh-keys \
    --aad-server-app-id $serverApplicationId \
    --aad-server-app-secret $serverApplicationSecret \
    --aad-client-app-id $clientApplicationId \
    --aad-tenant-id $tenantId

最後, 使用az aks get-認證命令取得叢集系統管理員認證。Finally, get the cluster admin credentials using the az aks get-credentials command. 在下列其中一個步驟中, 您會取得一般使用者叢集認證, 以查看作用中的 Azure AD 驗證流程。In one of the following steps, you get the regular user cluster credentials to see the Azure AD authentication flow in action.

az aks get-credentials --resource-group myResourceGroup --name $aksname --admin

建立 RBAC 繫結Create RBAC binding

必須先建立角色繫結或叢集角色繫結,Azure Active Directory 帳戶才能搭配 AKS 叢集使用。Before an Azure Active Directory account can be used with the AKS cluster, a role binding or cluster role binding needs to be created. 「角色」會定義要授與的權限,而「繫結」會將角色套用至需要的使用者。Roles define the permissions to grant, and bindings apply them to desired users. 這些指派可以套用至指定的命名空間或在整個叢集中套用。These assignments can be applied to a given namespace, or across the entire cluster. 如需詳細資訊, 請參閱使用 RBAC 授權For more information, see Using RBAC authorization.

使用az ad 登入-user show命令, 取得目前登入之使用者的使用者主體名稱 (UPN)。Get the user principal name (UPN) for the user currently logged in using the az ad signed-in-user show command. 在下一個步驟中, 此使用者帳戶已啟用 Azure AD 整合。This user account is enabled for Azure AD integration in the next step.

az ad signed-in-user show --query userPrincipalName -o tsv

重要

如果您授與的 RBAC 系結的使用者位於相同的 Azure AD 租使用者中, 請根據userPrincipalName指派許可權。If the user you grant the RBAC binding for is in the same Azure AD tenant, assign permissions based on the userPrincipalName. 如果使用者位於不同的 Azure AD 租使用者中, 請改為查詢並使用objectId屬性。If the user is in a different Azure AD tenant, query for and use the objectId property instead.

建立名為basic-azure-ad-binding.yaml的 YAML 資訊清單, 並貼上下列內容。Create a YAML manifest named basic-azure-ad-binding.yaml and paste the following contents. 在最後一行中, 將userPrincipalName_or_objectId取代為上一個命令中的 UPN 或物件識別碼輸出:On the last line, replace userPrincipalName_or_objectId with the UPN or object ID output from the previous command:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: contoso-cluster-admins
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: userPrincipalName_or_objectId

使用kubectl apply命令來建立 ClusterRoleBinding, 並指定 YAML 資訊清單的檔案名:Create the ClusterRoleBinding using the kubectl apply command and specify the filename of your YAML manifest:

kubectl apply -f basic-azure-ad-binding.yaml

透過 Azure AD 存取叢集Access cluster with Azure AD

現在讓我們來測試 AKS 叢集的 Azure AD authentication 整合。Now let's test the integration of Azure AD authentication for the AKS cluster. kubectl將設定內容設為使用一般使用者認證。Set the kubectl config context to use regular user credentials. 此內容會透過 Azure AD 將所有驗證要求傳遞回來。This context passes all authentication requests back through Azure AD.

az aks get-credentials --resource-group myResourceGroup --name $aksname --overwrite-existing

現在, 請使用kubectl get pod 命令來跨所有命名空間來查看 pod:Now use the kubectl get pods command to view pods across all namespaces:

kubectl get pods --all-namespaces

您會收到登入提示, 您可以使用網頁瀏覽器來使用 Azure AD 認證來進行驗證。You receive a sign in prompt to authenticate using Azure AD credentials using a web browser. 成功驗證之後, kubectl命令會顯示 AKS 叢集中的 pod, 如下列範例輸出所示:After you've successfully authenticated, the kubectl command displays the pods in the AKS cluster, as shown in the following example output:

$ kubectl get pods --all-namespaces

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code BYMK7UXVD to authenticate.

NAMESPACE     NAME                                    READY   STATUS    RESTARTS   AGE
kube-system   coredns-754f947b4-2v75r                 1/1     Running   0          23h
kube-system   coredns-754f947b4-tghwh                 1/1     Running   0          23h
kube-system   coredns-autoscaler-6fcdb7d64-4wkvp      1/1     Running   0          23h
kube-system   heapster-5fb7488d97-t5wzk               2/2     Running   0          23h
kube-system   kube-proxy-2nd5m                        1/1     Running   0          23h
kube-system   kube-svc-redirect-swp9r                 2/2     Running   0          23h
kube-system   kubernetes-dashboard-847bb4ddc6-trt7m   1/1     Running   0          23h
kube-system   metrics-server-7b97f9cd9-btxzz          1/1     Running   0          23h
kube-system   tunnelfront-6ff887cffb-xkfmq            1/1     Running   0          23h

已快取接收的kubectl驗證權杖。The authentication token received for kubectl is cached. 只有在權杖過期或重新建立 Kubernetes config 檔案時, 才會重複提示登入。You are only reprompted to sign in when the token has expired or the Kubernetes config file is re-created.

如果您在使用網頁瀏覽器成功登入後看到授權錯誤訊息, 如下列範例輸出所示, 請檢查下列可能的問題:If you see an authorization error message after you've successfully signed in using a web browser as in the following example output, check the following possible issues:

error: You must be logged in to the server (Unauthorized)
  • 您已定義適當的物件識別碼或 UPN, 視使用者帳戶是否位於相同的 Azure AD 租使用者而定。You defined the appropriate object ID or UPN, depending on if the user account is in the same Azure AD tenant or not.
  • 使用者不是 200 個以上的群組成員。The user is not a member of more than 200 groups.
  • 在伺服器的應用程式註冊中定義的密碼符合使用設定的值--aad-server-app-secretSecret defined in the application registration for server matches the value configured using --aad-server-app-secret

後續步驟Next steps

如需包含本文所示命令的完整腳本, 請參閱AKS 範例存放庫中的 Azure AD 整合腳本For the complete script that contains the commands shown in this article, see the Azure AD integration script in the AKS samples repo.

若要使用 Azure AD 的使用者和群組來控制叢集資源的存取權, 請參閱使用角色型存取控制來控制對叢集資源的存取, 並在 AKS 中 Azure AD身分識別。To use Azure AD users and groups to control access to cluster resources, see Control access to cluster resources using role-based access control and Azure AD identities in AKS.

如需如何保護 Kubernetes 叢集的詳細資訊, 請參閱AKS 的存取和身分識別選項)For more information about how to secure Kubernetes clusters, see Access and identity options for AKS).

如需身分識別和資源控制的最佳做法, 請參閱AKS 中驗證和授權的最佳作法For best practices on identity and resource control, see Best practices for authentication and authorization in AKS.