应用服务在 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.安装服务连接器无密码扩展
为Azure CLI安装最新的服务连接器无密码扩展:
az extension add --name serviceconnector-passwordless --upgrade
注意
请通过运行,检查扩展“serviceconnector-passwordless”的版本是否为“2.0.2”或更高版本。az version 可能需要先升级Azure CLI才能升级扩展版本。
2.创建无密码连接
接下来,使用服务连接器创建无密码连接。
小窍门
Azure门户可帮助你撰写以下命令。 在 Azure 门户中,转到 Azure 应用服务资源,从左侧菜单中选择 “服务连接器 ”,然后选择“ 创建”。 使用所有必需的参数填写表单。 Azure自动生成连接创建命令,可以在 CLI 中使用,也可以在Azure Cloud Shell中执行。
以下 Azure CLI 命令使用 --client-type 参数。
(可选)运行 az webapp connection create sql -h 以获取支持的客户端类型。
选择客户端类型并运行相应的命令。 请将下面的占位符替换为您自己的信息。
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <sql-group-name> \
--server <sql-name> \
--database <database-name> \
--user-identity client-id=<client-id> subs-id=<subscription-id> \
--client-type <client-type>
az webapp connection create sql \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <sql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
手动为Azure Database for MySQL灵活服务器设置Microsoft Entra身份验证。
(可选)运行 az webapp connection create mysql-flexible -h 命令以获取支持的客户端类型。
选择客户端类型并运行相应的命令。 以下 Azure CLI 命令使用 --client-type 参数。
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
az webapp connection create mysql-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <mysql-name> \
--database <database-name> \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type <client-type>
以下 Azure CLI 命令使用 --client-type 参数。
(可选)运行 az webapp connection create postgres-flexible -h 命令以获取所有支持的客户端类型的列表。
选择客户端类型并运行相应的命令。
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--user-identity client-id=XX subs-id=XX \
--client-type java
az webapp connection create postgres-flexible \
--resource-group <group-name> \
--name <server-name> \
--target-resource-group <group-name> \
--server <postgresql-name> \
--database <database-name> \
--system-identity \
--client-type <client-type>
授予对预先创建的表的权限
接下来,如果你在使用服务连接器之前已经在 PostgreSQL 灵活服务器中创建了表和序列,则你需要以所有者身份进行连接,并向服务连接器创建的 <aad-username> 授予权限。 服务连接器设置的连接字符串或配置中的用户名应类似于 aad_<connection name>。 如果使用 Azure 门户,请选择 Service Type 列旁边的展开按钮并获取值。 如果使用Azure CLI,请在 CLI 命令输出中检查 configurations。
然后,执行用于授予权限的查询。
az extension add --name rdbms-connect
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \"<aad-username>\";GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO \"<aad username>\";"
<owner-username> 和 <owner-password> 是现有表的所有者,可以向他人授予权限。
<aad-username> 是由服务连接器创建的用户。 将其替换为实际值。
通过此命令验证结果:
az postgres flexible-server execute -n <postgres-name> -u <owner-username> -p "<owner-password>" -d <database-name> --querytext "SELECT distinct(table_name) FROM information_schema.table_privileges WHERE grantee='<aad-username>' AND table_schema='public';" --output table
此服务连接器命令将在后台完成以下任务:
- 启用系统分配的托管标识,或为由Azure App Service托管的应用
<server-name>分配用户标识。
- 将 Microsoft Entra 管理员设置为当前登录用户。
- 为系统分配的托管标识或用户分配的托管标识添加数据库用户。 向此用户授予数据库
<database-name> 的所有权限。 可以在前面的命令输出中的connection string中找到用户名。
- 根据数据库类型将名为
AZURE_MYSQL_CONNECTIONSTRING、AZURE_POSTGRESQL_CONNECTIONSTRING 或 AZURE_SQL_CONNECTIONSTRING 的配置设置为Azure资源。
- 对于应用服务,配置是在“应用设置”边栏选项卡中设置的。
3、修改代码
安装依赖项。
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 mssql-python python-dotenv
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接配置。 对想要使用的身份验证类型的代码片段部分取消注释。
import os
from mssql_python import connect
server = os.getenv('AZURE_SQL_SERVER')
port = os.getenv('AZURE_SQL_PORT')
database = os.getenv('AZURE_SQL_DATABASE')
# Uncomment the following lines according to the authentication type.
# For system-assigned managed identity.
# connection_string = f'Server={server},{port};Database={database};Authentication=ActiveDirectoryMSI;Encrypt=yes;'
# For user-assigned managed identity.
# client_id = os.getenv('AZURE_SQL_USER')
# connection_string = f'Server={server},{port};Database={database};UID={client_id};Authentication=ActiveDirectoryMSI;Encrypt=yes;'
conn = connect(connection_string)
对于替代方法,还可以使用访问令牌连接到 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();
})();
4、设置开发环境
此示例代码使用 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 身份验证来开发和调试应用程序。
5、测试并发布
在开发环境中运行代码。 代码使用环境中的已登录 Microsoft Entra 用户连接到后端数据库。 用户可以访问数据库,因为其被配置为 Microsoft Entra 数据库管理员。
使用首选发布方法将代码发布到 Azure。 在应用服务中,代码使用应用的托管标识连接到后端数据库。
常见问题
托管标识是否支持 SQL Server?
本地 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 用户身份连接数据库。
- 为应用服务应用配置系统分配或用户分配的托管标识。
- 授予托管标识访问数据库的权限。
- 使用托管标识从您的代码(.NET Framework 4.8、.NET 6、Node.js、Python、Java)连接到 Azure 数据库。
- 以 Microsoft Entra 用户身份从开发环境连接到 Azure 数据库。