將 Azure 裝載的應用程式驗證給其他 Azure 資源的建議方法是使用 受控識別。
大部分的 Azure 服務都支援此方法,包括裝載於 Azure App Service、Azure 容器應用程式和 Azure 虛擬機器上的應用程式。 在 驗證概述 頁面上探索有關不同驗證技術和方法的更多資訊。 在前面的章節中,您將瞭解:
- 基本受控識別概念
- 如何為您的應用程式建立使用者指派的受控識別
- 如何將角色指派給使用者指派的受控識別
- 如何使用應用程式程式碼中的使用者指派受控識別進行驗證
基本受控識別概念
受控識別可讓您的應用程式安全地連線到其他 Azure 資源,而不需要使用秘密金鑰或其他應用程式秘密。 在內部,Azure 會追蹤身分識別,以及允許連線到的資源。 Azure 會使用此資訊來自動取得應用程式的 Microsoft Entra 權杖,以允許它連線到其他 Azure 資源。
設定裝載應用程式時,需要考慮兩種類型的受控識別:
-
系統指派的 受控識別會直接在 Azure 資源上啟用,並系結至其生命週期。 刪除資源時,Azure 會自動為您刪除身分識別。 系統指派的身分識別提供使用受控識別的最小方法。
-
使用者指派 的受控識別會建立為獨立的 Azure 資源,並提供更大的彈性和功能。 它們非常適合涉及需要共用相同身分識別和許可權的多個 Azure 資源的解決方案。 例如,如果多個虛擬機器需要存取同一組 Azure 資源,使用者指派的受控識別可提供可重複使用性和最佳化管理。
小提示
如需如何深入瞭解如何選取和管理系統指派和使用者指派的受控識別,請參閱 受控識別最佳做法建議 一文。
下列各節說明為 Azure 裝載的應用程式啟用和使用使用者指派的受控識別的步驟。 如果您需要使用系統指派的受控識別,請流覽 系統指派的受控識別 一文以取得詳細資訊。
建立使用者指派的受管理的身分識別
使用者指派的受控識別會使用 Azure 入口網站或 Azure CLI 在 Azure 訂用帳戶中建立為獨立資源。 Azure CLI 命令可以在 Azure Cloud Shell 或 已安裝 Azure CLI 的工作站上執行。
在 Azure 入口網站中,在主要搜尋列中輸入 受控識別 ,然後在 [服務 ] 區段下選取相符的結果。
在 [受控識別 ] 頁面上,選取 [+ 建立]。
在 [ 建立使用者指派的受控識別 ] 頁面上,選取使用者指派的受控識別的訂用帳戶、資源群組和區域,然後提供名稱。
選取 [ 檢閱 + 建立 ] 以檢閱和驗證您的輸入。
選取 [ 建立 ] 以建立使用者指派的受控識別。
建立身分識別之後,選取 [ 移至資源]。
在新身分識別的 [ 概觀 ] 頁面上,複製 [用戶端識別碼] 值,以便稍後在設定應用程式程式碼時使用。
使用 Azure CLI 命令 az identity create 來建立受控識別:
az identity create \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId' \
--output json
命令輸出會列印所建立使用者指派受控識別的用戶端識別碼。 用戶端 ID 可用來設定相依於身分識別的應用程式程式碼。
您一律可以使用命令 az identity show 再次檢視受控識別屬性:
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json
將受控識別指派給您的應用程式
使用者指派的受控識別可以與一或多個 Azure 資源相關聯。 使用該身分的所有資源都會取得透過身分角色套用的許可。
在 Azure 入口網站中,流覽至裝載應用程式程式碼的資源,例如 Azure App Service 或 Azure 容器應用程式執行個體。
從資源的 [概觀] 頁面中,展開 [設定],然後從導覽中選取 [身分識別]。
在身分識別頁面上,切換至使用者指派索引標籤。
選取 [+ 新增 ] 以開啟 [ 新增使用者指派的受控識別 ] 面板。
在 [ 新增使用者指派的受控識別 ] 面板上,使用 [ 訂用帳戶 ] 下拉式清單來篩選身分識別的搜尋結果。 使用 [使用者指派的受控識別 ] 搜尋方塊,找出您針對裝載應用程式的 Azure 資源啟用的使用者指派受控識別。
選取身分,然後選擇面板底部的 [ 新增 ] 以繼續。
Azure CLI 提供不同的命令,將使用者指派的受控識別指派給不同類型的裝載服務。
若要使用 Azure CLI 將使用者指派的受控識別指派給資源,例如 Azure App Service Web 應用程式,您需要身分識別的資源識別碼。 使用指令 az identity show 來擷取資源 ID:
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json \
--query id
取得資源識別碼之後,請使用 Azure CLI 命令 az <resourceType> identity assign 命令,將使用者指派的受控識別與不同的資源產生關聯,例如下列:
針對 Azure App Service,請使用 Azure CLI 命令 az webapp identity assign:
az webapp identity assign \
--resource-group <resource-group-name> \
--name <webapp-name> \
--identities <user-assigned-identity-resource-id>
針對 Azure Container Apps,請使用 Azure CLI 命令 az containerapp identity assign:
az containerapp identity assign \
--resource-group <resource-group-name> \
--name <containerapp-name> \
--identities <user-assigned-identity-resource-id>
針對 Azure 虛擬機器,請使用 Azure CLI 命令 az vm identity assign:
az vm identity assign \
--resource-group <resource-group-name> \
--name <vm-name> \
--identities <user-assigned-identity-resource-id>
將角色指派給受控識別
接下來,判斷您的應用程式需要哪些角色,並將這些角色指派給受控識別。 您可以在下列範圍將角色指派給受控識別:
-
資源:指派的角色僅適用於該特定資源。
-
資源群組:指派的角色會套用至資源群組中包含的所有資源。
-
訂用帳戶:指派的角色會套用至訂用帳戶中包含的所有資源。
下列範例示範如何在資源群組範圍指派角色,因為許多應用程式都會使用單一資源群組來管理其所有相關 Azure 資源。
流覽至資源群組的 [ 概觀 ] 頁面,其中包含具有使用者指派受控識別之應用程式。
選取左側導覽中的存取控制 (IAM)。
在 [ 存取控制 (IAM)] 頁面上,選取頂端功能表上的 [+ 新增 ],然後選擇 [ 新增角色指派 ] 以導覽至 [ 新增角色指派 ] 頁面。
新增 角色指派 頁面會呈現索引標籤式多步驟工作流程,可將角色指派給身分識別。 在初始 角色 索引標籤上,使用頂端的搜尋方塊來尋找您要指派給身分識別的角色。
從結果中選取角色,然後選擇 Next ( 下一步 ) 以移至 Members (成員) 索引標籤。
針對 [指派存取權] 選項,選取 [受控識別]。
針對 [成員] 選項,選擇 [+ 選取成員 ] 以開啟 [選取受控識別 ] 面板。
在 [ 選取受控識別 ] 面板上,使用 [訂用帳戶 ] 和 [受控識別] 下拉式清單來篩選身分識別的搜尋結果。 使用 [ 選取 搜尋] 方塊來尋找您針對裝載應用程式的 Azure 資源啟用的使用者指派受控識別。
選取身分識別,然後選擇面板底部的 [選取 ] 以繼續。
選取頁面底部的 檢閱 + 指派 。
在最終的 [ 檢閱 + 指派 ] 索引標籤上,選取 [ 檢閱 + 指派 ] 以完成工作流程。
若要使用 Azure CLI 將角色指派給使用者指派的受控識別,您需要身分識別的主體識別碼。 使用命令 az identity show 來擷取主體 ID:
az identity show \
--resource-group <your-resource-group> \
--name <your-managed-identity-name> \
--output json \
--query principalId
使用 az role definition list 命令來探索可以指派受控識別的角色:
az role definition list \
--query "sort_by([].{roleName:roleName, description:description}, &roleName)" \
--output table
使用 az role assignment create 命令將角色指派給受控識別:
az role assignment create \
--assignee <your-principal-id> \
--role <role-name> \
--scope <scope>
例如,若要允許具有讀取、寫入和刪除識別碼的 99999999-9999-9999-9999-999999999999 受控識別存取 Azure 儲存體 Blob 容器和資料,以存取 msdocs-sdk-auth-example 資源群組中的所有儲存體帳戶,請使用下列命令將應用程式服務主體指派給 儲存體 Blob 資料參與者 角色:
az role assignment create \
--assignee 99999999-9999-9999-9999-999999999999 \
--role "Storage Blob Data Contributor" \
--scope "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/msdocs-sdk-auth-example"
如需使用 Azure CLI 在資源或訂用帳戶層級指派許可權的相關資訊,請參閱使用 Azure CLI 指派 Azure 角色一文。
從您的應用程式向 Azure 服務進行驗證
Azure 身分識別程式庫提供各種認證 - 適合支援不同案例和 Microsoft Entra 驗證流程的實作TokenCredential。 由於受控識別在本機執行時無法使用,因此接下來的步驟示範在哪個案例中使用哪個認證:
實作程式碼
在JavaScript專案中,新增 @azure/身分套件 。 在您選擇的終端機中,導覽至應用程式專案目錄,然後執行下列命令:
npm install @azure/identity
Azure 服務是使用各種 Azure SDK 用戶端程式庫中的特製化用戶端類別來存取。 在 中 index.js,完成下列步驟以配置記號型鑑別:
- 匯入
@azure/identity 套件。
- 將適當的
TokenCredential 實例傳遞給用戶端:
- 當您的應用程式在本機執行時使用
DefaultAzureCredential 。
- 當您的應用程式在 Azure 中執行時使用
ManagedIdentityCredential ,並設定用戶端識別碼、資源識別碼或物件識別碼。
用戶端識別碼可用來在設定需要使用該身分識別進行驗證的應用程式或服務時識別受控識別。
使用下列命令擷取指派給使用者指派受控識別的用戶端識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId'
使用用戶端識別碼進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
console.log(process.env);
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const clientId = process.env.AZURE_CLIENT_ID;
if (!clientId) throw Error('AZURE_CLIENT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(clientId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
資源識別碼會使用下列結構,唯一識別 Azure 訂用帳戶內的受控識別資源:
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}
資源識別碼可以依慣例建置,這可讓您在環境中使用大量使用者指派的受控識別時更方便。
使用下列命令擷取使用者指派受控識別的資源識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'id'
使用資源識別碼進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const resourceId = process.env.AZURE_RESOURCE_ID;
if (!resourceId) throw Error('AZURE_RESOURCE_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(resourceId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
主體 ID 是物件 ID 的另一個名稱。
使用下列命令擷取使用者指派受控識別的物件識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'principalId'
使用物件 ID 進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient() {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const objectId = process.env.AZURE_OBJECT_ID;
if (!objectId) throw Error('AZURE_OBJECT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(objectId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main() {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME);
// do something with client
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
實作程式碼
在 TypeScript 專案中,新增 @azure/身分識別 套件。 在您選擇的終端機中,導覽至應用程式專案目錄,然後執行下列命令:
npm install typescript @azure/identity @types/node
Azure 服務是使用各種 Azure SDK 用戶端程式庫中的特製化用戶端類別來存取。 在 中 index.js,完成下列步驟以配置記號型鑑別:
- 匯入
@azure/identity 套件。
- 將適當的
TokenCredential 實例傳遞給用戶端:
- 當您的應用程式在本機執行時使用
DefaultAzureCredential
- 當您的應用程式在 Azure 中執行時使用
ManagedIdentityCredential ,並設定用戶端識別碼、資源識別碼或物件識別碼。
用戶端識別碼可用來在設定需要使用該身分識別進行驗證的應用程式或服務時識別受控識別。
使用下列命令擷取指派給使用者指派受控識別的用戶端識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'clientId'
使用用戶端識別碼進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const clientId = process.env.AZURE_CLIENT_ID;
if (!clientId) throw Error('AZURE_CLIENT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(clientId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
資源識別碼會使用下列結構,唯一識別 Azure 訂用帳戶內的受控識別資源:
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}
資源識別碼可以依慣例建置,這可讓您在環境中使用大量使用者指派的受控識別時更方便。
使用下列命令擷取使用者指派受控識別的資源識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'id'
使用資源識別碼進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const resourceId = process.env.AZURE_RESOURCE_ID;
if (!resourceId) throw Error('AZURE_RESOURCE_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(resourceId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
主體 ID 是物件 ID 的另一個名稱。
使用下列命令擷取使用者指派受控識別的物件識別碼:
az identity show \
--resource-group <resource-group-name> \
--name <identity-name> \
--query 'principalId'
使用物件 ID 進行設定 ManagedIdentityCredential :
import { BlobServiceClient } from '@azure/storage-blob';
import { ManagedIdentityCredential, DefaultAzureCredential } from '@azure/identity';
function createBlobServiceClient(): BlobServiceClient {
const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME;
if (!accountName) throw Error('Azure Storage accountName not found');
const url = `https://${accountName}.blob.core.windows.net`;
if (process.env.NODE_ENV === "production") {
const objectId = process.env.AZURE_OBJECT_ID;
if (!objectId) throw Error('AZURE_OBJECT_ID not found for Managed Identity');
return new BlobServiceClient(url, new ManagedIdentityCredential(objectId));
} else {
return new BlobServiceClient(url, new DefaultAzureCredential());
}
}
async function main(): Promise<void> {
try {
const blobServiceClient = createBlobServiceClient();
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_STORAGE_CONTAINER_NAME!);
const properties = await containerClient.getProperties();
console.log(properties);
} catch (err: any) {
console.error("Error retrieving container properties:", err.message);
throw err;
}
}
main().catch((err: Error) => {
console.error("Error running sample:", err.message);
process.exit(1);
});
上述程式碼的行為會因執行環境而異:
- 在本機開發工作站上,
DefaultAzureCredential 在環境變數中尋找應用程式服務主體,或在本機安裝的開發人員工具 (例如 Visual Studio Code) 中尋找一組開發人員認證。
- 部署至 Azure 時,
ManagedIdentityCredential 會探索您的受控識別設定,以自動向其他服務進行驗證。