应用服务在 Azure 中提供高度可缩放、自修补的 Web 托管服务。 它还为应用提供托管标识,这是一项统包解决方案,可以确保安全地访问 Azure SQL 数据库,包括:
应用服务的托管身份通过消除应用中的机密(如连接字符串中的凭据)来提高应用的安全性。 本教程介绍如何使用托管标识从应用服务连接到上述数据库。
要学习的知识:
- 将 Microsoft Entra 用户配置为 Azure 数据库的管理员。
- 以 Microsoft Entra 用户身份连接数据库。
- 为应用服务应用配置系统分配或用户分配的托管标识。
- 授予托管标识访问数据库的权限。
- 使用托管标识从您的代码(.NET Framework 4.8、.NET 6、Node.js、Python、Java)连接到 Azure 数据库。
- 以 Microsoft Entra 用户身份从开发环境连接到 Azure 数据库。
如果没有 Azure 订阅,可在开始前创建一个试用帐户。
- 基于 .NET、Node.js、Python 或 Java 在应用服务中创建应用。
- 使用 Azure SQL 数据库、Azure Database for MySQL 或 Azure Database for PostgreSQL 创建数据库服务器。
- 应熟悉标准连接模式(使用用户名和密码),并且能够成功从应用服务应用连接到所选的数据库。
为 Azure CLI 准备环境。
可以使用本地 Azure CLI。
1. 授予 Microsoft Entra 用户数据库访问权限
首先,通过将 Microsoft Entra 用户指定为服务器的管理员,对 Azure 数据库启用 Microsoft Entra 身份验证。 对于本教程中的方案,你将使用此用户从本地开发环境连接到 Azure 数据库。 稍后,为应用服务应用设置托管标识,以便从 Azure 中进行连接。
如果 Microsoft Entra 租户还没有用户,请按照使用 Microsoft Entra ID 添加或删除用户中的步骤创建一个用户。
使用 az ad user list
查找 Microsoft Entra 用户的对象 ID,并替换 <user-principal-name>。 结果会保存到变量中。
azureaduser=$(az ad user list --filter "userPrincipalName eq '<user-principal-name>'" --query [].id --output tsv)
使用 Azure CLI 中的 az sql server ad-admin create
命令,将此 Microsoft Entra 用户添加为 Active Directory 管理员。 在以下命令中,将<组名称>和<服务器名称>替换为你自己的参数。
az sql server ad-admin create --resource-group <group-name> --server-name <server-name> --display-name ADMIN --object-id $azureaduser
有关添加 Active Directory 管理员的详细信息,请参阅为服务器预配 Microsoft Entra 管理员
使用 Azure CLI 中的 az mysql server ad-admin create
命令,将此 Microsoft Entra 用户添加为 Active Directory 管理员。 在以下命令中,将<组名称>和<服务器名称>替换为你自己的参数。
az mysql server ad-admin create --resource-group <group-name> --server-name <server-name> --display-name <user-principal-name> --object-id $azureaduser
备注
此命令目前不适用于 Azure Database for MySQL 灵活服务器。
使用 Azure CLI 中的 az postgres server ad-admin create
命令,将此 Microsoft Entra 用户添加为 Active Directory 管理员。 在以下命令中,将<组名称>和<服务器名称>替换为你自己的参数。
az postgres server ad-admin create --resource-group <group-name> --server-name <server-name> --display-name <user-principal-name> --object-id $azureaduser
备注
此命令目前不适用于 Azure Database for PostgreSQL 灵活服务器。
接下来,配置应用服务应用,使用托管标识连接到 SQL 数据库。
在 Azure CLI 中使用 az webapp identity assign 命令,为应用服务应用启用托管标识。 在以下命令中,替换 <app-name>。
az webapp identity assign --resource-group <group-name> --name <app-name>
az webapp identity assign --resource-group <group-name> --name <app-name> --output tsv --query principalId
az ad sp show --id <output-from-previous-command> --output tsv --query appId
az ad sp show 的输出是系统分配的标识的应用程序 ID。 稍后需要用到此信息。
az webapp identity assign --resource-group <group-name> --name <app-name> --output tsv --query principalId
az ad sp show --id <output-from-previous-command> --output tsv --query appId
az ad sp show 的输出是系统分配的标识的应用程序 ID。 稍后需要用到此信息。
# Create a user-assigned identity and get its client ID
az identity create --name <identity-name> --resource-group <group-name> --output tsv --query "id"
# assign identity to app
az webapp identity assign --resource-group <group-name> --name <app-name> --identities <output-of-previous-command>
# get client ID of identity for later
az webapp identity show --name <identity-name> --resource-group <group-name> --output tsv --query "clientId"
az webapp identity show 的输出是用户分配的标识的客户端 ID。 稍后需要用到此信息。
备注
若要为部署槽位启用托管标识,请添加 --slot <slot-name>
,并在 <slot-name> 中使用槽名称。
需要向标识授予访问数据库的权限。 在 Azure CLI 中,使用以下命令登录到数据库。 将<替换为您的服务器名称,<替换为您的应用使用的数据库名称,<和>aad-password替换为您的Azure AD用户的凭据,从1、向Azure AD用户授予访问数据库的权限。
sqlcmd -S <server-name>.database.chinacloudapi.cn -d <database-name> -U <aad-user-name> -P "<aad-password>" -G -l 30
# Sign into Azure using the Azure AD user from "1. Grant database access to Azure AD user"
az login --allow-no-subscriptions
# Get access token for MySQL with the Azure AD user
az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken
# Sign into the MySQL server using the token
mysql -h <server-name>.mysql.database.chinacloudapi.cn --user <aad-user-name>@<server-name> --enable-cleartext-plugin --password=<token-output-from-last-command> --ssl
完整的用户名 <aad-user-name>@<server-name> 如 admin1@contoso.partner.onmschina.cn@mydbserver1
所示。
# Sign into Azure using the Azure AD user from "1. Grant database access to Azure AD user"
az login --allow-no-subscriptions
# Get access token for PostgreSQL with the Azure AD user
az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken
# Sign into the Postgres server
psql "host=<server-name>.postgres.database.chinacloudapi.cn port=5432 dbname=<database-name> user=<aad-user-name>@<server-name> password=<token-output-from-last-command>"
完整的用户名 <aad-user-name>@<server-name> 如 admin1@contoso.partner.onmschina.cn@mydbserver1
所示。
运行以下数据库命令以授予应用所需的权限。 例如,
CREATE USER [<app-name>] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [<app-name>];
ALTER ROLE db_datawriter ADD MEMBER [<app-name>];
ALTER ROLE db_ddladmin ADD MEMBER [<app-name>];
GO
对于部署槽位,请使用 <app-name>/slots/<slot-name> 而不是 <app-name>。
CREATE USER [<identity-name>] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [<identity-name>];
ALTER ROLE db_datawriter ADD MEMBER [<identity-name>];
ALTER ROLE db_ddladmin ADD MEMBER [<identity-name>];
GO
SET aad_auth_validate_oids_in_tenant = OFF;
CREATE AADUSER '<mysql-user-name>' IDENTIFIED BY '<application-id-of-system-assigned-identity>';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER ON *.* TO '<mysql-user-name>'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
无论你为 <mysql-user-name> 选择了什么名称,它都是你以后在应用服务中通过代码连接数据库时使用的 MySQL 用户。
SET aad_auth_validate_oids_in_tenant = OFF;
CREATE AADUSER '<mysql-user-name>' IDENTIFIED BY '<client-id-of-user-assigned-identity>';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER ON *.* TO '<mysql-user-name>'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
无论你为 <mysql-user-name> 选择了什么名称,它都是你以后在应用服务中通过代码连接数据库时使用的 MySQL 用户。
SET aad_validate_oids_in_tenant = off;
CREATE ROLE <postgresql-user-name> WITH LOGIN PASSWORD '<application-id-of-system-assigned-identity>' IN ROLE azure_ad_user;
无论为 <postgresql-user-name> 选择什么名称,该名称将是您以后从应用服务代码中连接到数据库时使用的 PostgreSQL 用户。
SET aad_validate_oids_in_tenant = off;
CREATE ROLE <postgresql-user-name> WITH LOGIN PASSWORD '<application-id-of-user-assigned-identity>' IN ROLE azure_ad_user;
无论你为 <postgresql-user-name> 选择什么名称,这将是你稍后用于从应用服务代码连接到数据库的 PostgreSQL 用户。
安装依赖项。
dotnet add package Microsoft.Data.SqlClient
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接字符串。
using Microsoft.Data.SqlClient;
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity:"Server=tcp:<server-name>.database.chinacloudapi.cn;Database=<database-name>;Authentication=Active Directory Default;TrustServerCertificate=True"
// For user-assigned managed identity: "Server=tcp:<server-name>.database.chinacloudapi.cn;Database=<database-name>;Authentication=Active Directory Default;User Id=<client-id-of-user-assigned-identity>;TrustServerCertificate=True"
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
有关详细信息,请参阅使用 Active Directory 托管标识身份验证。
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.4.6</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接字符串。
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class Main {
public static void main(String[] args) {
// AZURE_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.chinacloudapi.cn:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.chinacloudapi.cn:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("AZURE_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
有关详细信息,请参阅使用 Microsoft Entra 身份验证进行连接。
安装依赖项。
python -m pip install pyodbc
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接配置。 对想要使用的身份验证类型的代码片段部分取消注释。
import os;
import pyodbc
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
authentication = os.getenv('AZURE_SQL_AUTHENTICATION') # The value should be 'ActiveDirectoryMsi'
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};Authentication={authentication};Encrypt=yes;'
# For user-assigned managed identity.
# client_id = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server={server},{port};Database={database};UID={client_id};Authentication={authentication};Encrypt=yes;'
conn = pyodbc.connect(connString)
对于替代方法,还可以使用访问令牌连接到 Azure SQL 数据库,请参阅迁移 Python 应用程序以将无密码连接用于 Azure SQL 数据库。
- 安装依赖项。
npm install mssql
- 从服务连接器添加的环境变量中获取 Azure SQL 数据库连接配置。 对想要使用的身份验证类型的代码片段部分取消注释。
import sql from 'mssql';
const server = process.env.AZURE_SQL_SERVER;
const database = process.env.AZURE_SQL_DATABASE;
const port = parseInt(process.env.AZURE_SQL_PORT);
const authenticationType = process.env.AZURE_SQL_AUTHENTICATIONTYPE;
// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// authenticationType
// },
// options: {
// encrypt: true
// }
// };
// For user-assigned managed identity.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId
// }
// };
this.poolconnection = await sql.connect(config);
代码中与 Azure Database for MySQL 的连接遵循所有语言堆栈的 DefaultAzureCredential
模式。 DefaultAzureCredential
足够灵活,可以适应开发环境和 Azure 环境。 在本地运行时,它可以从所选的环境中 (Visual Studio、Visual Studio Code、Azure CLI 或Azure PowerShell) 检索已登录的 Azure 用户。 在 Azure 中运行时,它会检索托管标识。 因此,可以在开发时和生产环境中连接到数据库。 模式如下:
- 请从 Azure Identity 客户端库中实例化
DefaultAzureCredential
。 如果使用的是用户分配的标识,请指定标识的客户端 ID。
- 获取 Azure Database for MySQL 的访问令牌:
https://ossrdbms-aad.database.chinacloudapi.cn/.default
。
- 将令牌添加到连接字符串。
- 打开连接。
对于 .NET,请使用 Azure.Identity 等客户端库获取托管标识的访问令牌。 然后,使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines according to the authentication type.
// For system-assigned managed identity.
// var credential = new DefaultAzureCredential();
// For user-assigned managed identity.
// var credential = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// });
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.chinacloudapi.cn/.default" });
AccessToken accessToken = await credential.GetTokenAsync(tokenRequestContext);
// Open a connection to the MySQL server using the access token.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_MYSQL_CONNECTIONSTRING")};Password={accessToken.Token}";
using var connection = new MySqlConnection(connectionString);
Console.WriteLine("Opening connection using access token...");
await connection.OpenAsync();
// do something
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
从环境变量获取连接字符串,并添加插件名称以连接到数据库:
String url = System.getenv("AZURE_MYSQL_CONNECTIONSTRING");
String pluginName = "com.azure.identity.extensions.jdbc.mysql.AzureMysqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&defaultAuthenticationPlugin=" +
pluginName + "&authenticationPlugins=" + pluginName);
有关详细信息,请参阅将 Java 和 JDBC 与 Azure Database for MySQL 灵活服务器配合使用。
安装依赖项。
pip install azure-identity
# install Connector/Python https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
pip install mysql-connector-python
使用 azure-identity
库中的访问令牌进行身份验证。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import mysql.connector
import os
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# cred = ManagedIdentityCredential()
# For user-assigned managed identity.
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.chinacloudapi.cn/.default')
# open connect to Azure MySQL with the access token.
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token
cnx = mysql.connector.connect(user=user,
password=password,
host=host,
database=database)
cnx.close()
安装依赖项。
npm install --save @azure/identity
npm install --save mysql2
使用 @azure/identity
和 Azure MySQL 数据库信息从服务连接器添加的环境变量中获取访问令牌。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const mysql = require('mysql2');
// Uncomment the following lines according to the authentication type.
// for system-assigned managed identity
// const credential = new DefaultAzureCredential();
// for user-assigned managed identity
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.chinacloudapi.cn/.default');
const connection = mysql.createConnection({
host: process.env.AZURE_MYSQL_HOST,
user: process.env.AZURE_MYSQL_USER,
password: accessToken.token,
database: process.env.AZURE_MYSQL_DATABASE,
port: process.env.AZURE_MYSQL_PORT,
ssl: process.env.AZURE_MYSQL_SSL
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ' + err.stack);
return;
}
console.log('Connected to MySQL database');
});
代码中与 Azure Database for PostgreSQL 的连接遵循所有语言堆栈的 DefaultAzureCredential
模式。 DefaultAzureCredential
足够灵活,可以适应开发环境和 Azure 环境。 在本地运行时,它可以从所选的环境中 (Visual Studio、Visual Studio Code、Azure CLI 或Azure PowerShell) 检索已登录的 Azure 用户。 在 Azure 中运行时,它会检索托管标识。 因此,可以在开发时和生产环境中连接到数据库。 模式如下:
- 请从 Azure Identity 客户端库中实例化
DefaultAzureCredential
。 如果使用的是用户分配的标识,请指定标识的客户端 ID。
- 获取 Azure Database for PostgreSQL 的访问令牌:
https://ossrdbms-aad.database.chinacloudapi.cn/.default
。
- 将令牌添加到连接字符串。
- 打开连接。
对于 .NET,请使用 Azure.Identity 等客户端库获取托管标识的访问令牌。 然后,使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.chinacloudapi.cn/.default"
}));
// Combine the token with the connection string from the environment variables provided by Service Connector.
string connectionString =
$"{Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CONNECTIONSTRING")};Password={accessToken.Token}";
// Establish the connection.
using (var connection = new NpgsqlConnection(connectionString))
{
Console.WriteLine("Opening connection using access token...");
connection.Open();
}
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.5</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity-extensions</artifactId>
<version>1.2.0</version>
</dependency>
从环境变量获取连接字符串,并添加插件名称以连接到数据库:
import java.sql.*;
String url = System.getenv("AZURE_POSTGRESQL_CONNECTIONSTRING");
String pluginName = "com.Azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin";
Connection connection = DriverManager.getConnection(url + "&authenticationPluginClassName=" + pluginName);
有关详细信息,请参阅以下资源:
安装依赖项。
pip install azure-identity
pip install psycopg2-binary
使用 azure-identity
库中的访问令牌进行身份验证并将该令牌用作密码。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines according to the authentication type.
# For system-assigned identity.
# cred = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.chinacloudapi.cn/.default')
# Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
conn_string = os.getenv('AZURE_POSTGRESQL_CONNECTIONSTRING')
conn = psycopg2.connect(conn_string + ' password=' + accessToken.token)
安装依赖项。
npm install --save @azure/identity
npm install --save pg
在代码中,通过 @azure/identity
和 PostgreSQL 连接信息从服务连接器服务添加的环境变量中获取访问令牌。 合并它们来建立连接。 使用下面的代码时,请确保取消注释与你要使用的身份验证类型相对应的代码片段部分。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
const { Client } = require('pg');
// Uncomment the following lines according to the authentication type.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.chinacloudapi.cn/.default');
// Use the token and the connection information from the environment variables added by Service Connector to establish the connection.
(async () => {
const client = new Client({
host: process.env.AZURE_POSTGRESQL_HOST,
user: process.env.AZURE_POSTGRESQL_USER,
password: accesstoken.token,
database: process.env.AZURE_POSTGRESQL_DATABASE,
port: Number(process.env.AZURE_POSTGRESQL_PORT) ,
ssl: process.env.AZURE_POSTGRESQL_SSL
});
await client.connect();
await client.end();
})();
此代码示例使用 DefaultAzureCredential
通过 Microsoft Entra ID 获取一个可用的令牌,然后将其添加到 Azure 数据库连接中。 虽然可以自定义 DefaultAzureCredential
,但默认情况下已经非常灵活。 它从已登录的 Microsoft Entra 用户或托管标识获取令牌,具体取决于是在本地开发环境中运行还是在应用服务中运行。
无需进一步更改,代码即可在 Azure 中运行。 但是,若要在本地调试代码,开发环境需要已登录 Microsoft Entra 的用户。 在此步骤中,你将以 Microsoft Entra 用户身份登录来配置所选环境。
Visual Studio for Windows 集成了 Microsoft Entra 身份验证。 若要在 Visual Studio 中启用开发和调试,请在 Visual Studio 中添加 Microsoft Entra 用户,方法是从菜单中依次选择“文件”>“帐户设置”,然后选择“登录”或“添加”。
若要设置进行 Azure 服务身份验证的 Microsoft Entra 用户,请从菜单中依次选择“工具”>“选项”,然后依次选择“Azure 服务身份验证”>“帐户选择”。 选择已添加的 Microsoft Entra 用户,然后选择“确定”。
Visual Studio for Mac 未集成 Microsoft Entra 身份验证。 但是,您将稍后使用的 Azure 标识客户端库也可以从 Azure CLI 检索令牌。 若要在 Visual Studio 中启用开发和调试,请在本地计算机上安装 Azure CLI。
以 Microsoft Entra 用户身份通过以下命令登录到 Azure CLI:
az login --allow-no-subscriptions
Visual Studio Code 已通过 Azure 扩展与 Microsoft Entra 身份验证集成。 在 Visual Studio Code 中安装 Azure Tools 扩展。
在 Visual Studio Code 的活动栏上,选择 Azure 徽标。
在“应用服务”资源管理器中,选择“登录到 Azure...”,然后按照说明进行操作。
稍后将使用的 Azure 标识客户端库可以从 Azure CLI 中使用令牌。 若要启用基于命令行的开发,请在本地计算机上安装 Azure CLI。
以 Microsoft Entra 用户身份通过以下命令登录到 Azure:
az login --allow-no-subscriptions
稍后将使用的 Azure 标识客户端库可以从 Azure PowerShell 中使用令牌。 若要启用基于命令行的开发,请在本地计算机上安装 Azure PowerShell。
以 Microsoft Entra 用户身份通过以下 cmdlet 登录到 Azure CLI:
Connect-AzAccount -Environment AzureChinaCloud
有关为 Microsoft Entra 身份验证设置开发环境的详细信息,请参阅适用于 .NET 的 Azure 标识客户端库。
现已准备好将 SQL 数据库作为后端,使用 Microsoft Entra 身份验证来开发和调试应用程序。
在开发环境中运行代码。 代码使用环境中的已登录 Microsoft Entra 用户连接到后端数据库。 用户可以访问数据库,因为其被配置为 Microsoft Entra 数据库管理员。
使用首选发布方法将代码发布到 Azure。 在应用服务中,代码使用应用的托管标识连接到后端数据库。
本地 SQL Server 不支持 Microsoft Entra ID 和托管标识。
我收到错误 Login failed for user '<token-identified principal>'.
你尝试为其请求令牌的托管标识未获授权访问 Azure 数据库。
我更改了应用服务身份验证或关联的应用注册。 为什么我仍然得到旧令牌?
托管标识的后端服务还保留一个令牌缓存,只有在过期的情况下才更新目标资源的令牌。 如果在尝试使用应用获取令牌后修改配置,则在缓存的令牌过期之前,你实际上不会获得具有更新权限的新令牌。 解决此问题的最佳方式是使用新的 InPrivate (Edge) /private (Safari) /Incognito (Chrome) 窗口测试更改。 这样,就可以确保从一个经过身份验证的新会话开始。
如何将托管标识添加到 Microsoft Entra 组?
如果你愿意,可以将标识添加到 Microsoft Entra 组,然后将访问权限授予 Microsoft Entra 组,而不是授予标识。 例如,以下命令将上一步中的托管标识添加到名为 myAzureSQLDBAccessGroup 的新组:
groupid=$(az ad group create --display-name myAzureSQLDBAccessGroup --mail-nickname myAzureSQLDBAccessGroup --query objectId --output tsv)
msiobjectid=$(az webapp identity show --resource-group <group-name> --name <app-name> --query principalId --output tsv)
az ad group member add --group $groupid --member-id $msiobjectid
az ad group member list -g $groupid
若要为 Microsoft Entra 组授予数据库权限,请参阅相应数据库类型的文档。
我遇到错误 SSL connection is required. Please specify SSL options and retry
。
连接到 Azure 数据库需要其他设置,并且超出了本教程的范围。 有关详细信息,请参阅下列相应链接:
在 Azure Database for PostgreSQL 中配置 TLS 连接 - 单一服务器在应用程序中配置 SSL 连接,以便安全地连接到 Azure Database for MySQL
你已了解:
- 将 Microsoft Entra 用户配置为 Azure 数据库的管理员。
- 以 Microsoft Entra 用户身份连接数据库。
- 为应用服务应用配置系统分配或用户分配的托管标识。
- 授予托管标识访问数据库的权限。
- 使用 Azure 的托管身份从您的代码 (.NET Framework 4.8、.NET 6、Node.js、Python、Java) 连接到 Azure 数据库。
- 以 Microsoft Entra 用户身份从开发环境连接到 Azure 数据库。