使用 Azure CLI 将 Azure Active Directory 与 Azure Kubernetes 服务集成Integrate 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 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:

  • Azure AD 只能在支持 RBAC 的群集上启用。Azure AD can only be enabled on RBAC-enabled cluster.
  • Azure AD 传统集成只能在创建群集期间启用。Azure AD legacy integration can only be enabled during cluster creation.

准备阶段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. 以下示例使用名称 myaksclusterThe 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 membership 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 service principal needs permissions to perform the following actions:

  • 读取目录数据Read directory data
  • 登录并读取用户配置文件Sign in and read user profile

使用 az ad app permission 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 permission 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 permission admin-consent 来请求管理许可: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

使用 az ad app show 命令获取服务器应用的 oAuth2 ID,以允许两个应用组件之间的身份验证流。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 ID。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 permission 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 permission 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. 以下示例在 ChinaEast2 区域中创建资源组:The following example creates the resource group in the ChinaEast2 region:

为群集创建资源组:Create a resource group for the cluster:

az group create --name myResourceGroup --location ChinaEast2

使用 az account show 命令获取 Azure 订阅的租户 ID。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 群集的命令可提供服务器和客户端应用程序 ID、服务器应用程序服务主体机密和租户 ID: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-credentials 命令获取群集管理员凭据。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

在对 AKS 群集使用 Azure Active Directory 帐户之前,需要创建角色绑定或群集角色绑定。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 signed-in-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 或对象 ID 输出: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 命令创建群集角色绑定,并指定 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 身份验证集成。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 pods 命令查看所有命名空间中的 pod:Now use the kubectl get pods command to view pods across all namespaces:

kubectl get pods --all-namespaces

你将收到一条登录提示,指出在 Web 浏览器中使用 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://aka.ms/deviceloginchina 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 配置文件时,系统才会再次提示登录。You are only reprompted to sign in when the token has expired or the Kubernetes config file is re-created.

如果在使用 Web 浏览器成功登录后看到了以下示例输出中所示的授权错误消息,请检查以下问题: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)
  • 你定义了适当的对象 ID 或 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-secret 配置的值相匹配Secret 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.