使用服務主體進行 Azure 驗證

本文探討 Azure 身分識別連結庫如何透過服務主體支援 Microsoft Entra 令牌驗證。 本文涵蓋下列主題:

如需詳細資訊,請參閱 Microsoft Entra ID 中的應用程式和服務主體物件。 如需針對服務主體驗證問題進行疑難解答,請參閱 針對服務主體驗證進行疑難解答。

使用 Azure CLI 建立服務主體

使用下列 Azure CLI 範例來建立或取得客戶端密碼認證。

使用下列命令來建立服務主體,並設定其對 Azure 資源的存取:

az ad sp create-for-rbac \
    --name <your application name> \
    --role Contributor \
    --scopes /subscriptions/mySubscriptionID

這個指令會傳回類似下列輸出的值:

{
"appId": "generated-app-ID",
"displayName": "dummy-app-name",
"name": "http://dummy-app-name",
"password": "random-password",
"tenant": "tenant-ID"
}

使用下列命令來建立服務主體以及憑證。 記下此憑證的路徑/位置。

az ad sp create-for-rbac \
    --name <your application name> \
    --role Contributor \
    --cert <certificate name> \
    --create-cert

檢查傳回的認證,並記下下列資訊:

  • AZURE\_CLIENT\_ID for the appId.
  • AZURE\_CLIENT\_SECRET 用於密碼。
  • AZURE\_TENANT\_ID 租使用者。

用戶端密碼認證

此認證會透過其用戶端密碼(密碼)驗證已建立的服務主體。 此範例示範如何使用 從 azure-security-keyvault-secrets 用戶端連結庫驗證 。SecretClientClientSecretCredential

/**
 *  Authenticate with client secret.
 */
ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
  .clientId("<your client ID>")
  .clientSecret("<your client secret>")
  .tenantId("<your tenant ID>")
  .build();

// Azure SDK client builders accept the credential as a parameter.
SecretClient client = new SecretClientBuilder()
  .vaultUrl("https://<your Key Vault name>.vault.azure.net")
  .credential(clientSecretCredential)
  .buildClient();

用戶端憑證認證

此認證會透過其客戶端憑證驗證已建立的服務主體。 此範例示範如何使用 從 azure-security-keyvault-secrets 用戶端連結庫驗證 。SecretClientClientCertificateCredential

/**
 *  Authenticate with a client certificate.
 */
ClientCertificateCredential clientCertificateCredential = new ClientCertificateCredentialBuilder()
  .clientId("<your client ID>")
  .pemCertificate("<path to PEM certificate>")
  // Choose between either a PEM certificate or a PFX certificate.
  //.pfxCertificate("<path to PFX certificate>", "PFX CERTIFICATE PASSWORD")
  .tenantId("<your tenant ID>")
  .build();

// Azure SDK client builders accept the credential as a parameter.
SecretClient client = new SecretClientBuilder()
  .vaultUrl("https://<your Key Vault name>.vault.azure.net")
  .credential(clientCertificateCredential)
  .buildClient();

下一步

本文涵蓋透過服務主體的驗證。 這種形式的驗證是您可以在適用於 Java 的 Azure SDK 中驗證的多種方式之一。 下列文章說明其他方式:

如果您遇到與服務主體驗證相關的問題,請參閱 針對服務主體驗證進行疑難解答。

掌握驗證之後,請參閱 在 Azure SDK for Java 中設定記錄,以取得 SDK 所提供的記錄功能相關信息。