使用 Azure CLI 來建立 Azure 服務主體Create an Azure service principal with Azure CLI

使用 Azure 服務的自動化工具應一律具有權限限制。Automated tools that use Azure services should always have restricted permissions. Azure 提供的服務主體,可替代以具有完整權限的使用者身分登入應用程式。Instead of having applications sign in as a fully privileged user, Azure offers service principals.

Azure 服務主體是一種身分識別,建立目的是為了搭配應用程式、託管服務及自動化工具來存取 Azure 資源。An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access Azure resources. 此存取會受限於指派給服務主體的角色,以便您控制可存取的資源,以及在哪個層級上存取。This access is restricted by the roles assigned to the service principal, giving you control over which resources can be accessed and at which level. 基於安全理由,我們建議您一律搭配自動化工具使用服務主體,而不是讓服務主體透過使用者身分識別來登入。For security reasons, it's always recommended to use service principals with automated tools rather than allowing them to log in with a user identity.

本文會示範搭配 Azure CLI 建立服務主體,以及對服務主體進行資訊擷取和重設的步驟。This article shows you the steps for creating, getting information about, and resetting a service principal with the Azure CLI.

建立服務主體Create a service principal

使用 az ad sp create-for-rbac 命令建立服務主體。Create a service principal with the az ad sp create-for-rbac command. 建立服務主體時,您可以選擇其所用的登入驗證類型。When creating a service principal, you choose the type of sign-in authentication it uses.

注意

如果您的帳戶沒有建立服務主體的權限,az ad sp create-for-rbac 會傳回「權限不足,無法完成作業」的錯誤訊息。If your account doesn't have permission to create a service principal, az ad sp create-for-rbac will return an error message containing "Insufficient privileges to complete the operation." 請連絡您的 Azure Active Directory 管理員,以建立服務主體。Contact your Azure Active Directory admin to create a service principal.

有兩種驗證類型可用於服務主體:密碼式驗證和憑證式驗證。There are two types of authentication available for service principals: Password-based authentication, and certificate-based authentication.

密碼式驗證Password-based authentication

密碼式驗證沒有任何驗證參數,而是搭配使用為您建立的隨機密碼。Without any authentication parameters, password-based authentication is used with a random password created for you.

az ad sp create-for-rbac --name ServicePrincipalName

重要

自 Azure CLI 2.0.68 版開始,不再支援 --password 參數透過使用者定義的密碼建立服務主體,以避免意外使用弱式密碼。As of Azure CLI 2.0.68, the --password parameter to create a service principal with a user-defined password is no longer supported to prevent the accidental use of weak passwords.

搭配密碼驗證使用的服務主體輸出包含 password 索引鍵。The output for a service principal with password authentication includes the password key. __請務必__複製此值 (此值無法擷取)。Make sure you copy this value - it can't be retrieved. 如果您忘記密碼,請重設服務主體認證If you forget the password, reset the service principal credentials.

appIdtenant 索引鍵會出現在 az ad sp create-for-rbac 的輸出中,並且用於服務主體驗證。The appId and tenant keys appear in the output of az ad sp create-for-rbac and are used in service principal authentication. 請記錄其值,但這些值可以隨時透過 az ad sp list 來擷取。Record their values, but they can be retrieved at any point with az ad sp list.

憑證式驗證Certificate-based authentication

針對憑證式驗證,請使用 --cert 引數。For certificate-based authentication, use the --cert argument. 此引數需要您保留現有憑證。This argument requires that you hold an existing certificate. 請確定使用此服務主體的任何工具皆可存取憑證的私密金鑰。Make sure any tool that uses this service principal has access to the certificate's private key. 憑證應使用 ASCII 格式,例如 PEM、CER 或 DER。Certificates should be in an ASCII format such as PEM, CER, or DER. 將憑證傳遞為字串,或使用 @path 格式從檔案載入憑證。Pass the certificate as a string, or use the @path format to load the certificate from a file.

az ad sp create-for-rbac --name ServicePrincipalName --cert "-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----"
az ad sp create-for-rbac --name ServicePrincipalName --cert @/path/to/cert.pem

您可以新增 --keyvault 引數,以使用 Azure Key Vault 中的憑證。The --keyvault argument can be added to use a certificate in Azure Key Vault. 在此案例中,--cert 值是憑證的名稱。In this case, the --cert value is the name of the certificate.

az ad sp create-for-rbac --name ServicePrincipalName --cert CertName --keyvault VaultName

若要建立用於驗證的「自我簽署」 憑證,請使用 --create-cert 引數:To create a self-signed certificate for authentication, use the --create-cert argument:

az ad sp create-for-rbac --name ServicePrincipalName --create-cert

您可以新增 --keyvault 引數,將憑證儲存在 Azure Key Vault。The --keyvault argument can be added to store the certificate in Azure Key Vault. 使用 --keyvault 時,--cert 引數為__必要項目__。When using --keyvault, the --cert argument is required.

az ad sp create-for-rbac --name ServicePrincipalName --create-cert --cert CertName --keyvault VaultName

除非您將憑證儲存在 Key Vault,否則輸出會包含 fileWithCertAndPrivateKey 索引鍵。Unless you store the certificate in Key Vault, the output includes the fileWithCertAndPrivateKey key. 此索引鍵的值會告訴您產生的憑證儲存在何處。This key's value tells you where the generated certificate is stored. __務必__將憑證複製到安全的位置,否則您會無法使用此服務主體來登入。Make sure that you copy the certificate to a secure location, or you can't sign in with this service principal.

針對儲存在 Key Vault 中的憑證,可使用 az keyvault secret show 來擷取憑證的私密金鑰。For certificates stored in Key Vault, retrieve the certificate's private key with az keyvault secret show. 在 Key Vault 中,憑證的祕密名稱會與憑證名稱相同。In Key Vault, the name of the certificate's secret is the same as the certificate name. 如果您無法存取憑證的私密金鑰,請重設服務主體認證If you lose access to a certificate's private key, reset the service principal credentials.

appIdtenant 索引鍵會出現在 az ad sp create-for-rbac 的輸出中,並且用於服務主體驗證。The appId and tenant keys appear in the output of az ad sp create-for-rbac and are used in service principal authentication. 請記錄其值,但這些值可以隨時透過 az ad sp list 來擷取。Record their values, but they can be retrieved at any point with az ad sp list.

取得現有的服務主體Get an existing service principal

租用戶中的服務主體清單,可以使用 az ad sp list 來擷取。A list of the service principals in a tenant can be retrieved with az ad sp list. 依預設,此命令會傳回您租用戶的前 100 個服務主體。By default this command returns the first 100 service principals for your tenant. 若要取得所有租用戶的服務主體,請使用 --all 引數。To get all of a tenant's service principals, use the --all argument. 取得這份清單可能需要很長的時間,建議您使用下列其中一個引數來篩選清單:Getting this list can take a long time, so it's recommended that you filter the list with one of the following arguments:

  • --display-name 會要求服務主體的「前置詞」 符合所提供的名稱。--display-name requests service principals that have a prefix that match the provided name. 服務主體的顯示名稱是建立期間使用 --name 參數所設定的值。The display name of a service principal is the value set with the --name parameter during creation. 如果您未在服務主體建立期間設定 --name,則名稱前置詞會是 azure-cli-If you didn't set --name during service principal creation, the name prefix is azure-cli-.
  • --spn 會以確切的服務主體名稱比對進行篩選。--spn filters on exact service principal name matching. 服務主體名稱一律以 https:// 開頭。The service principal name always starts with https://. 如果您用於 --name 的值不是 URI,則此值會是後面接著顯示名稱的 https://if the value you used for --name wasn't a URI, this value is https:// followed by the display name.
  • --show-mine 會要求僅限已登入使用者建立的服務主體。--show-mine requests only service principals created by the signed-in user.
  • --filter 採用 OData 篩選,而且會執行「伺服器端」 的篩選。--filter takes an OData filter, and performs server-side filtering. 比起使用 CLI 的 --query 引數來篩選用戶端,我們較建議您使用此方法。This method is recommended over filtering client-side with the CLI's --query argument. 若要深入了解 OData 篩選,請參閱用於篩選的 OData 運算式語法To learn about OData filters, see OData expression syntax for filters.

傳回的服務主體物件資訊是詳細資訊。The information returned for service principal objects is verbose. 若只要取得登入所需的資訊,請使用查詢字串 [].{"id":"appId", "tenant":"appOwnerTenantId"}To get only the information necessary for sign-in, use the query string [].{"id":"appId", "tenant":"appOwnerTenantId"}. 例如,若要取得由目前已登入使用者所建立的所有服務主體登入資訊:For example, to get the sign-in information for all service principals created by the currently logged in user:

az ad sp list --show-mine --query '[].{"id":"appId", "tenant":"appOwnerTenantId"}'

重要

az ad sp listaz ad sp show 會取得使用者和租用戶,但不含任何驗證祕密「或」 驗證方法。az ad sp list or az ad sp show get the user and tenant, but not any authentication secrets or the authentication method. 您可以使用 az keyvault secret show 來擷取 Key Vault 中憑證的祕密,但預設不會儲存任何其他祕密。Secrets for certificates in Key Vault can be retrieved with az keyvault secret show, but no other secrets are stored by default. 如果您忘記驗證方法或祕密,請重設服務主體認證If you forget an authentication method or secret, reset the service principal credentials.

管理服務主體角色Manage service principal roles

Azure CLI 使用下列命令來管理角色指派:The Azure CLI has the following commands to manage role assignments:

服務主體的預設角色是參與者The default role for a service principal is Contributor. 此角色具有讀取和寫入至 Azure 帳戶的完整權限。This role has full permissions to read and write to an Azure account. 讀者角色的權限較為侷限,僅有唯讀存取權。The Reader role is more restrictive, with read-only access. 如需角色型存取控制 (RBAC) 和角色的詳細資訊,請參閱 RBAC:內建角色For more information on Role-Based Access Control (RBAC) and roles, see RBAC: Built-in roles.

此範例會新增讀者角色,並移除參與者角色:This example adds the Reader role and removes the Contributor one:

az role assignment create --assignee APP_ID --role Reader
az role assignment delete --assignee APP_ID --role Contributor

注意

如果您的帳戶沒有足夠權限可指派角色,您會看到錯誤訊息,這表示您的帳戶「沒有執行 'Microsoft.Authorization/roleAssignments/write' 動作的權限」。請連絡您的 Azure Active Directory 管理員,以管理角色。If your account doesn't have permission to assign a role, you see an error message that your account "does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write'." Contact your Azure Active Directory admin to manage roles.

新增角色「不會」 限制之前指派的權限。Adding a role doesn't restrict previously assigned permissions. 限制服務主體的權限時,應移除「參與者」 角色。When restricting a service principal's permissions, the Contributor role should be removed.

列出指派的角色可以驗證變更:The changes can be verified by listing the assigned roles:

az role assignment list --assignee APP_ID

使用服務主體來登入Sign in using a service principal

藉由登入來測試新服務主體的認證和權限。Test the new service principal's credentials and permissions by signing in. 若要使用服務主體登入,您需要 appIdtenant 和認證。To sign in with a service prinicpal, you need the appId, tenant, and credentials.

透過服務主體來使用密碼登入:To sign in with a service principal using a password:

az login --service-principal --username APP_ID --password PASSWORD --tenant TENANT_ID

若要使用憑證登入,該憑證必須是可在本機使用的 PEM 或 DER 檔案,並且採用 ASCII 格式:To sign in with a certificate, it must be available locally as a PEM or DER file, in ASCII format:

az login --service-principal --username APP_ID --tenant TENANT_ID --password /path/to/cert

若要深入了解如何使用服務主體登入,請參閱使用 Azure CLI 登入To learn more about signing in with a service principal, see Sign in with the Azure CLI.

重設認證Reset credentials

如果您忘記服務主體的認證,請使用 az ad sp credential resetIf you forget the credentials for a service principal, use az ad sp credential reset. 重設命令會使用與 az ad sp create-for-rbac 相同的引數。The reset command takes the same arguments as az ad sp create-for-rbac.

az ad sp credential reset --name APP_ID