对大多数 Azure 服务的应用程序请求必须使用密钥或无密码连接进行身份验证。 开发人员必须尽量避免在不安全的位置公开密钥。 能够访问密钥的任何人都可以对服务进行身份验证。 与帐户密钥相比,无密钥身份验证具有更好的管理和安全优势,因为无需存储密钥(或连接字符串)。
通过以下步骤启用无密钥连接:
- 配置身份验证。
- 根据需要设置环境变量。
- 使用 Azure 标识库凭据类型创建 Azure OpenAI 客户端对象。
身份验证
若要使用 Azure 客户端库,需要对 Microsoft Entra ID 进行身份验证。
身份验证因运行应用的环境而异:
Azure OpenAI 无键构建基块
使用以下链接浏览 Azure OpenAI 无密钥构建基块 AI 模板。 此模板使用用户帐户 RBAC 角色权限预配 Azure OpenAI 帐户,以便对无密钥(Microsoft Entra)身份验证进行访问 OpenAI API SDK。
注意
本文使用一个或多个 AI 应用模板作为本文中的示例和指南的基础。 AI 应用模板为你提供了维护良好、易于部署的参考实现,可帮助确保 AI 应用有一个高质量的起点。
对本地开发进行身份验证
选择一个工具,在本地开发过程中用于身份验证。
重要
若要在本地开发期间访问 Azure 资源,必须使用分配给该角色的 Azure 帐户Azure AI Developer。 例如,Visual Studio 或 Azure CLI。
对 Azure 托管的环境进行身份验证
查找使用 Azure OpenAI 的角色。 根据你打算如何设置该角色,需要名称或 ID。
| 角色名称 |
角色 ID |
| 对于 Azure CLI 或 Azure PowerShell,可以使用角色名称。 |
对于 Bicep,需要角色 ID。 |
使用下表选择角色和 ID。
| 用例 |
角色名称 |
角色 ID |
| 助手 |
Cognitive Services OpenAI Contributor |
a001fd3d-188f-4b5d-821b-7da978bf7442 |
| 聊天完成 |
Cognitive Services OpenAI User |
5e0bd9bd-7b93-4f28-af87-19fc36ad61bd |
选择要使用的标识类型。
-
个人标识:与登录到 Azure 相关的个人标识。
-
托管标识:由 Azure 管理和创建以在 Azure 上使用的标识。 对于托管标识,创建一个用户分配的托管标识。 创建托管标识时,需要
Client ID,也称为 app ID。
要查找你的个人标识,请使用以下命令之一。 在下一步中,将 ID 用作 <identity-id>。
对于本地开发,若要获取自己的标识 ID,请使用以下命令。 在使用此命令之前,需要使用 az login 登录。
az ad signed-in-user show \
--query id -o tsv
对于本地开发,若要获取自己的标识 ID,请使用以下命令。 在使用此命令之前,需要使用 Connect-AzAccount 登录。
(Get-AzContext).Account.ExtendedProperties.HomeAccountId.Split('.')[0]
使用通过 Azure 开发人员 CLI 部署的 Bicep 时,运行部署的人员或服务的标识设置为 principalId 参数。
以下 main.parameters.json 变量设置为运行进程的标识。
"principalId": {
"value": "${AZURE_PRINCIPAL_ID}"
},
若要在 Azure 中使用,请将用户分配的托管标识指定为 Bicep 部署过程的一部分。 创建一个与运行进程的标识分开的用户分配的托管标识。
resource userAssignedManagedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = {
name: managedIdentityName
location: location
}
将基于角色的访问控制 (RBAC) 角色分配给资源组的标识。
若要通过 RBAC 授予你对资源的标识权限,请使用 Azure CLI 命令 az role assignment create 分配角色。
az role assignment create \
--role "Cognitive Services OpenAI User" \
--assignee "<identity-id>" \
--scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>"
若要通过 RBAC 向你的 Azure OpenAI 资源授予应用程序权限,请使用 Azure PowerShell cmdlet New-AzRoleAssignment 分配角色。
New-AzRoleAssignment -ObjectId "<identity-id>" -RoleDefinitionName "Cognitive Services OpenAI User" -Scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>"
使用以下 Azure OpenAI Bicep 模板创建资源,并为 identityId 设置身份验证。 Bicep 需要角色 ID。 此 Bicep 代码片段中显示的 name 不是 Azure 角色;它特定于 Bicep 部署。
// main.bicep
param environment string = 'production'
// USER ROLES
module openAiRoleUser 'core/security/role.bicep' = {
scope: openAiResourceGroup
name: 'openai-role-user'
params: {
principalId: (environment == 'development') ? principalId : userAssignedManagedIdentity
principalType: (environment == 'development') ? 'User' : 'ServicePrincipal'
roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd'
}
}
从 main.bicep 中调用以下通用 Bicep 以创建任何角色。
// core/security/role.bicep
metadata description = 'Creates a role assignment for an identity.'
param principalId string // passed in from main.bicep identityId
@allowed([
'Device'
'ForeignGroup'
'Group'
'ServicePrincipal'
'User'
])
param principalType string = 'ServicePrincipal'
param roleDefinitionId string
resource role 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(subscription().id, resourceGroup().id, principalId, roleDefinitionId)
properties: {
principalId: principalId
principalType: principalType
roleDefinitionId: resourceId('Microsoft.Authorization/roleDefinitions', roleDefinitionId)
}
}
如果适用,请将 <identity-id>、<subscription-id> 和 <resource-group-name> 替换为实际值。
若要连接到 Azure OpenAI,代码需要知道资源终结点,可能需要其他环境变量。
为 Azure OpenAI 终结点创建环境变量。
-
AZURE_OPENAI_ENDPOINT:此 URL 是 Azure OpenAI 资源的访问点。
根据应用运行的位置创建环境变量:
| 位置 |
标识 |
说明 |
| Local |
个人 |
对于具有个人标识的本地运行时,请登录以使用工具创建凭据。 |
| Azure 云 |
用户分配的托管标识 |
创建一个 AZURE_CLIENT_ID 环境变量,其中包含要进行身份验证的用户分配托管标识的客户端 ID。 |
安装 Azure 标识客户端库
使用以下链接安装 Azure 标识客户端库。
安装 Go Azure 标识客户端库:
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
使用以下 POM 文件安装 Java Azure 标识客户端库:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.10.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
安装 JavaScript Azure 标识客户端库:
npm install --save @azure/identity
使用 DefaultAzureCredential
Azure 标识库的 DefaultAzureCredential 允许客户在本地开发环境和 Azure 云中运行相同的代码。
有关 .NET DefaultAzureCredential 的详细信息,请参阅 DefaultAzureCredential 概述。
使用以下方法之一设置用户分配的托管标识的客户端 ID:
设置环境变量 AZURE_CLIENT_ID。 无参数构造函数 DefaultAzureCredential 在存在时使用此环境变量的值。
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
using System;
using static System.Environment;
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
OpenAIClient client = new(new Uri(endpoint), new DefaultAzureCredential());
在 上设置属性 DefaultAzureCredentialOptions:
using Azure;
using Azure.AI.OpenAI;
using Azure.Identity;
using System;
using static System.Environment;
string endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
var credential = new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = "<user_assigned_client_id>"
});
OpenAIClient client = new(new Uri(endpoint), credential);
有关 DefaultAzureCredential for Go 的详细信息,请参阅DefaultAzureCredential概述。
import (
"log"
"github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
dac, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
client, err := azopenai.NewClient(os.Getenv("AZURE_OPENAI_ENDPOINT"), dac, nil)
if err != nil {
log.Fatalf("ERROR: %s", err)
}
_ = client
}
有关 java DefaultAzureCredential 的详细信息,请参阅 DefaultAzureCredential 概述。
使用以下方法之一设置用户分配的托管标识的客户端 ID:
设置环境变量 AZURE_CLIENT_ID。 无参数构造函数 DefaultAzureCredential 使用此环境变量的值(如果存在)。
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
OpenAIClient client = new OpenAIClientBuilder()
.credential(credential)
.endpoint(endpoint)
.buildClient();
通过使用 DefaultAzureCredential 配置客户端 ID,为 DefaultAzureCredentialBuilder 指定一个特定的用户分配的托管标识:
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.ai.openai.OpenAIClient;
import com.azure.ai.openai.OpenAIClientBuilder;
String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
String userAssignedClientId = "<your managed identity client ID>";
TokenCredential dacWithUserAssignedManagedIdentity
= new DefaultAzureCredentialBuilder().managedIdentityClientId(userAssignedClientId).build();
OpenAIClient client = new OpenAIClientBuilder()
.credential(dacWithUserAssignedManagedIdentity)
.endpoint(endpoint)
.buildClient();
有关 JavaScript DefaultAzureCredential 的详细信息,请参阅 DefaultAzureCredential 概述。
使用以下方法之一设置用户分配的托管标识的客户端 ID:
设置环境变量 AZURE_CLIENT_ID。 如果此环境变量存在,则无参数构造函数 DefaultAzureCredential 使用其值。
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { AzureOpenAI } from "openai";
const credential = new DefaultAzureCredential();
const scope = "https://cognitiveservices.azure.com/.default";
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
const deployment = "<your Azure OpenAI deployment name>";
const apiVersion = "2024-05-01-preview";
const options = { azureADTokenProvider, deployment, apiVersion, endpoint }
const client = new AzureOpenAI(options);
通过使用 DefaultAzureCredential 参数配置客户端 ID,为 managedIdentityClientId 指定一个特定的用户分配的托管标识:
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { AzureOpenAI } from "openai";
const managedIdentityClientId = "<your managed identity client ID>";
const credential = new DefaultAzureCredential({
managedIdentityClientId: managedIdentityClientId,
});
const scope = "https://cognitiveservices.azure.com/.default";
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
const endpoint = process.env["AZURE_OPENAI_ENDPOINT"] || "<endpoint>";
const deployment = "<your Azure OpenAI deployment name>";
const apiVersion = "2024-05-01-preview";
const options = { azureADTokenProvider, deployment, apiVersion, endpoint }
const client = new AzureOpenAI(options);
有关 Python DefaultAzureCredential 的详细信息,请参阅 DefaultAzureCredential 概述。
使用以下方法之一设置用户分配的托管标识的客户端 ID:
设置环境变量 AZURE_CLIENT_ID。 无参数构造函数 DefaultAzureCredential 会使用此环境变量的值(如果存在)。
import openai
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default")
openai_client = openai.AzureOpenAI(
api_version=os.getenv("AZURE_OPENAI_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_ad_token_provider=token_provider
)
通过使用 DefaultAzureCredential 参数配置客户端 ID,为 managed_identity_client_id 指定一个特定的用户分配的托管标识:
import openai
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
user_assigned_client_id = "<your managed identity client ID>"
credential = DefaultAzureCredential(
managed_identity_client_id=user_assigned_client_id
)
token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
openai_client = openai.AzureOpenAI(
api_version=os.getenv("AZURE_OPENAI_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
azure_ad_token_provider=token_provider
)
资源