无密码连接使用托管标识来访问 Azure 服务。 使用此方法,无需手动跟踪和管理托管标识的机密。 这些任务由 Azure 在内部安全地进行处理。
服务连接器可在 Azure Spring Apps、Azure 应用服务和 Azure 容器应用等应用托管服务中启用托管标识。 服务连接器还会在 Microsoft Fabric 中配置数据库服务(如 Azure Database for PostgreSQL、Azure Database for MySQL、Azure SQL 数据库和 SQL 数据库)以接受托管标识。
在本教程中,你将使用 Azure CLI 完成以下任务:
- 使用 Azure CLI 检查初始环境。
- 使用服务连接器创建无密码连接。
- 使用服务连接器生成的环境变量或配置来访问数据库服务。
先决条件
- 具有活动订阅的 Azure 帐户。 免费创建 Azure 帐户。
- 一个部署到服务连接器支持的区域中的 Azure 应用服务的应用。
- Azure CLI 2.61.0 或更高版本。
开始使用 Azure CLI:
安装服务连接器无密码扩展
为 Azure CLI 安装最新服务连接器无密码扩展:
az extension add --name serviceconnector-passwordless --upgrade
注意
请通过运行,检查扩展“serviceconnector-passwordless”的版本是否为“2.0.2”或更高版本。az version
可能需要先升级 Azure CLI 才能升级扩展版本。
创建无密码连接
接下来,我们将以 Azure 应用服务为例,使用托管标识来创建连接。
如果使用:
注意
如果使用 Azure 门户,请转到 Azure 应用服务、Azure Spring Apps 或 Azure 容器应用的“服务连接器”边栏选项卡,然后选择“创建”以创建连接。 Azure 门户将自动编写命令,并在 Cloud Shell 上触发命令执行。
以下 Azure CLI 命令使用--client-type
参数,可以是 java、dotnet、python 等。运行az webapp connection create postgres-flexible -h
以获取支持的客户端类型,并选择与应用程序匹配的客户端类型。
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type $CLIENT_TYPE
az webapp connection create postgres-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $POSTGRESQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX\
--client-type $CLIENT_TYPE
Azure Database for MySQL 灵活服务器需要用户分配的托管标识才能启用 Microsoft Entra 身份验证。 有关详细信息,请参阅设置 Azure Database for MySQL 灵活服务器的 Microsoft Entra 身份验证。 可以使用以下命令创建用户分配的托管标识:
USER_IDENTITY_NAME=<YOUR_USER_ASSIGNED_MANAGED_IDENTITY_NAME>
IDENTITY_RESOURCE_ID=$(az identity create \
--name $USER_IDENTITY_NAME \
--resource-group $RESOURCE_GROUP \
--query id \
--output tsv)
重要说明
创建用户分配的托管标识后,请让全局管理员或特权角色管理员为此标识授予以下权限:
User.Read.All
GroupMember.Read.All
Application.Read.All
有关详细信息,请参阅 Active Directory 身份验证的权限部分。
接下来,使用服务连接器将应用连接到具有系统分配的托管标识的 MySQL 数据库。
以下 Azure CLI 命令使用 --client-type
参数。 运行az webapp connection create mysql-flexible -h
以获取支持的客户端类型,并选择与应用程序匹配的客户端类型。
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--system-identity mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
az webapp connection create mysql-flexible \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $MYSQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX mysql-identity-id=$IDENTITY_RESOURCE_ID \
--client-type java
以下 Azure CLI 命令使用 --client-type
参数。 运行az webapp connection create sql -h
以获取支持的客户端类型,并选择与应用程序匹配的客户端类型。
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--system-identity \
--client-type dotnet
az webapp connection create sql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--target-resource-group $RESOURCE_GROUP \
--server $SQL_HOST \
--database $DATABASE_NAME \
--service-principal client-id=XX secret=XX \
--client-type dotnet
以下 Azure CLI 命令使用 --client-type
参数。 运行az webapp connection create fabricsql -h
以获取支持的客户端类型,并选择与应用程序匹配的客户端类型。
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--user-identity client-id=XX subs-id=XX \
--client-type dotnet
az webapp connection create fabricsql \
--resource-group $RESOURCE_GROUP \
--name $APPSERVICE_NAME \
--fabric-workspace-uuid $FABRIC_WORKSPACE_UUID \
--fabric-sql-db-uuid $FABRIC_SQL_DB_UUID \
--system-identity \
--client-type dotnet
注意
在 Microsoft Fabric 中将 SQL 数据库作为目标时,不支持使用服务主体的服务连接。
此服务连接器命令将在后台完成以下任务:
- 启用系统分配的托管标识,或为 Azure 应用服务/Azure Spring Apps/Azure 容器应用托管的应用
$APPSERVICE_NAME
分配用户标识。
- 如果以前未启用,请为数据库服务器启用 Microsoft Entra Authentication。
- 将 Microsoft Entra 管理员设置为当前已登录用户。
- 为系统分配的托管标识、用户分配的托管标识或服务主体添加数据库用户。 向此用户授予数据库
$DATABASE_NAME
的所有权限。 可以在上述命令输出的连接字符串中找到用户名。
- 根据数据库类型,将命名为
AZURE_MYSQL_CONNECTIONSTRING
、AZURE_POSTGRESQL_CONNECTIONSTRING
、AZURE_SQL_CONNECTIONSTRING
或FABRIC_SQL_CONNECTIONSTRING
的配置设置到 Azure 资源上。
- 对于应用服务,配置是在“应用设置”边栏选项卡中设置的。
- 对于 Spring Apps,配置是在应用程序启动时设置的。
- 对于容器应用,配置设置为环境变量。 可以在 Azure 门户的“服务连接器”边栏选项卡中获取所有配置及其值。
服务连接器将向用户分配以下权限,你可以撤销这些权限,并根据要求进行调整。
GRANT ALL PRIVILEGES ON DATABASE "$DATABASE_NAME" TO "username";
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO "username";
GRANT ALL PRIVILEGES ON $DATABASE_NAME.* TO 'username'@'%';
GRANT CONTROL ON DATABASE::"$DATABASE_NAME" TO "username";
ALTER ROLE db_datareader ADD MEMBER "username"
ALTER ROLE db_datawriter ADD MEMBER "username"
ALTER ROLE db_ddladmin ADD MEMBER "username"
通过 Microsoft Entra 身份验证连接到数据库
创建连接后,可以使用应用程序中的连接字符串通过 Microsoft Entra 身份验证连接到数据库。 例如,可使用以下解决方案通过 Microsoft Entra 身份验证连接到数据库。
对于 .NET,没有用于支持无密码连接的插件或库。 可使用 Azure.Identity 等客户端库获取托管标识或服务主体的访问令牌。 然后,可使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
using Azure.Identity;
using Azure.Core;
using Npgsql;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var sqlServerTokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_POSTGRESQL_CLIENTSECRET");
// var sqlServerTokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await sqlServerTokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]
{
"https://ossrdbms-aad.database.windows.net/.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
pip freeze > requirements.txt # Save the dependencies to a file
使用 azure-identity
库获取访问令牌并使用该令牌作为密码。 从服务连接器添加的环境变量中获取连接信息。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# 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)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.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)
安装依赖项。
pip install azure-identity
使用服务连接器添加的环境变量使用 azure-identity
库获取访问令牌。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import DefaultAzureCredential
import psycopg2
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# credential = DefaultAzureCredential()
# For user-assigned identity.
# managed_identity_client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal.
# tenant_id = os.getenv('AZURE_POSTGRESQL_TENANTID')
# client_id = os.getenv('AZURE_POSTGRESQL_CLIENTID')
# client_secret = os.getenv('AZURE_POSTGRESQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Acquire the access token.
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在设置文件中,从服务连接器服务添加的环境变量中获取 Azure PostgreSQL 数据库信息。 使用上一步中获取的 accessToken
来访问数据库。
# In your setting file, eg. settings.py
host = os.getenv('AZURE_POSTGRESQL_HOST')
user = os.getenv('AZURE_POSTGRESQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
database = os.getenv('AZURE_POSTGRESQL_NAME')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host,
'PORT': '5432', # Port is 5432 by default
'OPTIONS': {'sslmode': 'require'},
}
}
安装依赖项。
go get github.com/lib/pq
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,使用 azidentity
获取访问令牌,然后将它用作密码并使用服务连接器提供的连接信息来连接到 Azure PostgreSQL。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"database/sql"
"fmt"
"os"
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
_ "github.com/lib/pq"
)
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_POSTGRESQL_CLIENTID")
// tenantid := os.Getenv("AZURE_POSTGRESQL_TENANTID")
// clientsecret := os.Getenv("AZURE_POSTGRESQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
// error handling
}
// Acquire the access token
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
// Combine the token with the connection string from the environment variables added by Service Connector to establish the connection.
connectionString := os.Getenv("AZURE_POSTGRESQL_CONNECTIONSTRING") + " password=" + token.Token
conn, err := sql.Open("postgres", connectionString)
if err != nil {
panic(err)
}
conn.Close()
安装依赖项。
npm install --save @azure/identity
npm install --save pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 @azure/identity
获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential, ClientSecretCredential } from "@azure/identity";
import { Client } from 'pg';
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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
// });
// For service principal.
// const tenantId = process.env.AZURE_POSTGRESQL_TENANTID;
// const clientId = process.env.AZURE_POSTGRESQL_CLIENTID;
// const clientSecret = process.env.AZURE_POSTGRESQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.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();
})();
对于 PHP,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
在代码中,使用 REST API 使用你喜欢的库获取访问令牌。
对于用户分配的标识和系统分配的标识,应用服务和容器应用提供了一个内部可访问的 REST 终结点,它通过定义两个环境变量(IDENTITY_ENDPOINT
和 IDENTITY_HEADER
)来检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
通过向标识终结点发出 HTTP GET 请求来获取访问令牌,并在查询中将 https://ossrdbms-aad.database.windows.net
用作 resource
。 对于用户分配的标识,请同时在查询中包含服务连接器添加的环境变量中的客户端 ID。
有关服务主体,请参阅 Azure AD 服务到服务访问令牌请求,来查看如何获取访问令牌的详细信息。 发出范围为 https://ossrdbms-aad.database.windows.net/.default
的 POST 请求,并使用服务连接器添加的环境变量中的服务主体的租户 ID、客户端 ID 和客户端密码。
将访问令牌和服务连接器服务添加的环境变量中的 PostgreSQL 连接字符串相结合来建立连接。
<?php
$conn_string = sprintf("%s password=", getenv('AZURE_POSTGRESQL_CONNECTIONSTRING'), $access_token);
$dbconn = pg_connect($conn_string);
?>
对于 Ruby,没有用于无密码连接的插件或库。 可以获取托管标识或服务主体的访问令牌,并将其用作连接到数据库的密码。 可使用 Azure REST API 获取访问令牌。
安装依赖项。
gem install pg
在代码中,使用服务连接器服务添加的环境变量中的 PostgreSQL 连接信息使用 REST API 获取访问令牌。 组合使用它们来建立连接。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
应用服务和容器应用提供内部可访问的 REST 终结点用于检索托管标识的令牌。 有关详细信息,请查看 REST 终结点参考。
require 'pg'
require 'dotenv/load'
require 'net/http'
require 'json'
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned identity.
# uri = URI(ENV['IDENTITY_ENDPOINT'] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01')
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For user-assigned identity.
# uri = URI(ENV[IDENTITY_ENDPOINT] + '?resource=https://ossrdbms-aad.database.windows.net&api-version=2019-08-01&client_id=' + ENV['AZURE_POSTGRESQL_CLIENTID'])
# res = Net::HTTP.get_response(uri, {'X-IDENTITY-HEADER' => ENV['IDENTITY_HEADER'], 'Metadata' => 'true'})
# For service principal
# uri = URI('https://login.microsoftonline.com/' + ENV['AZURE_POSTGRESQL_TENANTID'] + '/oauth2/v2.0/token')
# params = {
# :grant_type => 'client_credentials',
# :client_id: => ENV['AZURE_POSTGRESQL_CLIENTID'],
# :client_secret => ENV['AZURE_POSTGRESQL_CLIENTSECRET'],
# :scope => 'https://ossrdbms-aad.database.windows.net/.default'
# }
# req = Net::HTTP::POST.new(uri)
# req.set_form_data(params)
# req['Content-Type'] = 'application/x-www-form-urlencoded'
# res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
# http.request(req)
parsed = JSON.parse(res.body)
access_token = parsed["access_token"]
# Use the token and the connection string from the environment variables added by Service Connector to establish the connection.
conn = PG::Connection.new(
connection_string: ENV['AZURE_POSTGRESQL_CONNECTIONSTRING'] + " password=" + access_token,
)
若要更详细地了解如何获取服务主体的访问令牌,请参阅 Azure AD 服务到服务访问令牌请求。
接下来,如果你在使用服务连接器之前已经在 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
对于 .NET,没有用于支持无密码连接的插件或库。 可使用 Azure.Identity 等客户端库获取托管标识或服务主体的访问令牌。 然后,可使用访问令牌作为密码来连接到数据库。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
using Azure.Core;
using Azure.Identity;
using MySqlConnector;
// Uncomment the following lines corresponding to the authentication type you want to use.
// 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");
// });
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_MYSQL_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_MYSQL_CLIENTSECRET");
// var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(
new[] { "https://ossrdbms-aad.database.windows.net/.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";
Properties properties = new Properties();
properties.put("defaultAuthenticationPlugin", pluginName);
properties.put("authenticationPlugins", pluginName);
// Uncomment the following lines corresponding to the authentication type you want to use.
// for user-assigned managed identity
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// properties.put("azure.clientId", clientId);
// For service principal
// String tenantId = System.getenv('AZURE_MYSQL_TENANTID')
// String clientId = System.getenv('AZURE_MYSQL_CLIENTID')
// String clientSecret = System.getenv('AZURE_MYSQL_CLIENTSECRET')
// properties.put("azure.clientId", clientId);
// properties.put("azure.clientSecret", clientSecret);
// properties.put("azure.tenantId", tenantId);
Connection connection = DriverManager.getConnection(url, properties);
有关详细信息,请参阅将 Java 和 JDBC 与 Azure Database for MySQL 灵活服务器配合使用。
对于 Spring 应用程序,如果使用 --client-type springboot
选项创建连接,则服务连接器会为 Azure Spring Apps 设置 spring.datasource.azure.passwordless-enabled
、spring.datasource.url
和 spring.datasource.username
属性。
按照“将 Azure Database for MySQL 实例连接到 Azure Spring Apps 中的应用程序”教程中的说明更新应用程序。 请记住删除 spring.datasource.password
配置属性(如果之前已设置),并将正确的依赖项添加到 Spring 应用程序中。
有关更多教程,请参阅将 Spring Data 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 corresponding to the authentication type you want to use.
# 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)
# For service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.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()
安装依赖项。
pip install azure-identity
通过 azure-identity
库使用服务连接器添加的环境变量获取访问令牌。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
import os
# Uncomment the following lines corresponding to the authentication type you want to use.
# system-assigned managed identity
# cred = ManagedIdentityCredential()
# user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# service principal
# tenant_id = os.getenv('AZURE_MYSQL_TENANTID')
# client_id = os.getenv('AZURE_MYSQL_CLIENTID')
# client_secret = os.getenv('AZURE_MYSQL_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# acquire token
accessToken = cred.get_token('https://ossrdbms-aad.database.windows.net/.default')
在设置文件中,从服务连接器服务添加的环境变量中获取 Azure MySQL 数据库信息。 使用上一步中获取的 accessToken
来访问数据库。
# in your setting file, eg. settings.py
host = os.getenv('AZURE_MYSQL_HOST')
database = os.getenv('AZURE_MYSQL_NAME')
user = os.getenv('AZURE_MYSQL_USER')
password = accessToken.token # this is accessToken acquired from above step.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': database,
'USER': user,
'PASSWORD': password,
'HOST': host
}
}
安装依赖项。
go get "github.com/go-sql-driver/mysql"
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,通过 azidentity
获取访问令牌,然后使用令牌连接到 Azure MySQL。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/go-sql-driver/mysql"
)
func main() {
// Uncomment the following lines corresponding to the authentication type you want to use.
// for system-assigned managed identity
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// for user-assigned managed identity
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// for service principal
// clientid := os.Getenv("AZURE_MYSQL_CLIENTID")
// tenantid := os.Getenv("AZURE_MYSQL_TENANTID")
// clientsecret := os.Getenv("AZURE_MYSQL_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
if err != nil {
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string("https://ossrdbms-aad.database.windows.net/.default"),
})
connectionString := os.Getenv("AZURE_MYSQL_CONNECTIONSTRING") + ";Password=" + token.Token
db, err := sql.Open("mysql", connectionString)
}
安装依赖项
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 corresponding to the authentication type you want to use.
// 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
// });
// for service principal
// const tenantId = process.env.AZURE_MYSQL_TENANTID;
// const clientId = process.env.AZURE_MYSQL_CLIENTID;
// const clientSecret = process.env.AZURE_MYSQL_CLIENTSECRET;
// const credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
// acquire token
var accessToken = await credential.getToken('https://ossrdbms-aad.database.windows.net/.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 数据库,而无需使用密钥。
安装依赖项。
dotnet add package Microsoft.Data.SqlClient
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接字符串。
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("AZURE_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
有关详细信息,请参阅使用 Active Directory 托管标识身份验证。
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</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.windows.net:1433;databaseName={SQLDbName};authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};msiClientId={UserAssignedMiClientId};authentication=ActiveDirectoryMSI;"
// For service principal: "jdbc:sqlserver://{SQLName}.database.windows.net:1433;databaseName={SQLDbName};user={ServicePrincipalClientId};password={spSecret};authentication=ActiveDirectoryServicePrincipal;"
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();
}
}
}
有关详细信息,请参阅使用托管标识从应用服务连接到 Azure 数据库,而无需使用密钥。
对于 Spring 应用程序,如果使用 --client-type springboot
选项创建连接,则服务连接器会为 Azure Spring Apps 设置采用值格式 spring.datasource.url
的 jdbc:sqlserver://<sql-server>.database.windows.net:1433;databaseName=<sql-db>;authentication=ActiveDirectoryMSI;
属性。
按照“迁移 Java 应用程序以将无密码连接用于 Azure SQL 数据库”教程中的说明更新应用程序。 请记住删除 spring.datasource.password
配置属性(如果之前已设置),并添加正确的依赖项。
安装依赖项。
python -m pip install pyodbc
从服务连接器添加的环境变量中获取 Azure SQL 数据库连接配置。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。 如果使用 Azure 容器应用作为计算服务或者代码片段中的连接字符串不起作用,请参阅迁移 Python 应用程序以将无密码连接用于 Azure SQL 数据库来使用访问令牌连接到 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')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity.
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For user-assigned managed identity.
# clientID = os.getenv('AZURE_SQL_USER')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={clientID};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
# For service principal.
# user = os.getenv('AZURE_SQL_USER')
# password = os.getenv('AZURE_SQL_PASSWORD')
# connString = f'Driver={{ODBC Driver 18 for SQL Server}};Server=tcp:{server},{port};Database={database};UID={user};PWD={password};Authentication={authentication};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30'
conn = pyodbc.connect(connString)
- 安装依赖项。
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 corresponding to the authentication type you want to use.
// For system-assigned managed identity.
// const config = {
// server,
// port,
// database,
// authentication: {
// type: 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
// }
// };
// For service principal.
// const clientId = process.env.AZURE_SQL_CLIENTID;
// const clientSecret = process.env.AZURE_SQL_CLIENTSECRET;
// const tenantId = process.env.AZURE_SQL_TENANTID;
// const config = {
// server,
// port,
// database,
// authentication: {
// type: authenticationType
// },
// options: {
// encrypt: true,
// clientId: clientId,
// clientSecret: clientSecret,
// tenantId: tenantId
// }
// };
this.poolconnection = await sql.connect(config);
有关详细信息,请参阅 Microsoft SQL Server 客户端编程的主页。
安装依赖项。
dotnet add package Microsoft.Data.SqlClient
从 Service Connector 添加的环境变量中检索 Microsoft Fabric 连接字符串中的 SQL 数据库。
using Microsoft.Data.SqlClient;
string connectionString =
Environment.GetEnvironmentVariable("FABRIC_SQL_CONNECTIONSTRING")!;
using var connection = new SqlConnection(connectionString);
connection.Open();
有关详细信息,请参阅 使用 Active Directory 托管标识身份验证。
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>10.2.0.jre11</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.7.0</version>
</dependency>
从 Service Connector 添加的环境变量中检索 Microsoft Fabric 连接字符串中的 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) {
// FABRIC_SQL_CONNECTIONSTRING should be one of the following:
// For system-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;"
// For user-assigned managed identity: "jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;msiClientId=<msiClientId>;authentication=ActiveDirectoryMSI;"
String connectionString = System.getenv("FABRIC_SQL_CONNECTIONSTRING");
SQLServerDataSource ds = new SQLServerDataSource();
ds.setURL(connectionString);
try (Connection connection = ds.getConnection()) {
System.out.println("Connected successfully.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
有关详细信息,请参阅使用托管标识从应用服务连接到 Azure 数据库,而无需使用密钥。
对于 Spring 应用程序,如果使用选项--client-type springboot
创建连接,服务连接器会将值格式FABRIC_SQL_CONNECTIONSTRING
的环境变量jdbc:sqlserver://<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;databaseName=<SQL-DB-name>-<Fabric-DB-Identifier>;authentication=ActiveDirectoryMSI;
设置为 Azure Spring Apps。
为用户分配的托管标识添加了 msiClientId=<msiClientId>;
。
按照“迁移 Java 应用程序以将无密码连接用于 Azure SQL 数据库”教程中的说明更新应用程序。 请记住,如果之前已设置了 spring.datasource.password
配置属性,请将其删除,并添加正确的依赖项。
spring:
datasource:
url: ${FABRIC_SQL_CONNECTIONSTRING}
安装依赖项。
python -m pip install pyodbc
从 Service Connector 添加的环境变量中检索 Microsoft Fabric 连接字符串中的 SQL 数据库。 如果使用 Azure 容器应用作为计算服务或代码片段中的连接字符串不起作用,请参阅 迁移 Python 应用程序以使用 Azure SQL 数据库的无密码连接,以使用无密码 凭据连接到 Microsoft Fabric 中的 SQL 数据库。 使用托管标识进行连接时,连接字符串中 Authentication=ActiveDirectoryMSI;
是必需的。 UID=<msiClientId>
在使用用户分配的托管标识进行连接时,是连接字符串中必需的一个组件。
import os
import pyodbc, struct
from azure.identity import DefaultAzureCredential
connStr = os.getenv('FABRIC_SQL_CONNECTIONSTRING')
# System-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;Authentication=ActiveDirectoryMSI;`
# User-assigned managed identity connection string format
# `Driver={ODBC Driver 17 for SQL Server};Server=tcp:<Fabric-SQL-Identifier>.msit-database.fabric.microsoft.com,1433;Database=<SQL-DB-name>-<Fabric-DB-Identifier>;UID=<msiClientId>;Authentication=ActiveDirectoryMSI;`
conn = pyodbc.connect(connString)
- 安装依赖项。
go mod init <YourProjectName>
go mod tidy
- 从 Service Connector 添加的环境变量中检索 Microsoft Fabric 连接字符串中的 SQL 数据库。
package main
import (
"github.com/microsoft/go-mssqldb/azuread"
"database/sql"
"context"
"log"
"fmt"
"os"
)
var db *sql.DB
var connectionString = os.Getenv("FABRIC_SQL_CONNECTIONSTRING")
func main() {
var err error
// Create connection pool
db, err = sql.Open(azuread.DriverName, connectionString)
if err != nil {
log.Fatal("Error creating connection pool: ", err.Error())
}
ctx := context.Background()
err = db.PingContext(ctx)
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("Connected!\n")
}
有关详细信息,请参阅 使用 Golang 查询 Azure SQL 数据库中的数据库。
有关详细信息,请参阅 Microsoft Fabric 中的“连接到 SQL 数据库”。
将应用程序部署到 Azure 托管服务
将应用程序部署到 Azure 托管服务。 (可选)请参阅下方指南了解有关如何部署这些资源的详细信息。
检查日志或调用应用程序以查看它是否可以成功连接到 Azure 数据库。
疑难解答
权限
如果遇到任何与权限相关的错误,请使用命令 az account show
确认 Azure CLI 已登录用户。 请确保使用正确的帐户登录。 接下来,确认你拥有使用服务连接器创建无密码连接可能需要的以下权限。
权限 |
操作 |
Microsoft.DBforPostgreSQL/flexibleServers/read |
需要此权限才能获取数据库服务器信息 |
Microsoft.DBforPostgreSQL/flexibleServers/write |
需要此权限才能为数据库服务器启用 Microsoft Entra 身份验证 |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/write |
需要此权限才能创建防火墙规则以防本地 IP 地址被阻止 |
Microsoft.DBforPostgreSQL/flexibleServers/firewallRules/delete |
需要此权限才能还原服务连接器创建的防火墙规则以避免安全问题 |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/read |
需要此权限才能检查 Azure CLI 登录用户是否为数据库服务器 Microsoft Entra 管理员 |
Microsoft.DBforPostgreSQL/flexibleServers/administrators/write |
需要此权限才能将 Azure CLI 登录用户添加为数据库服务器 Microsoft Entra 管理员 |
权限 |
操作 |
Microsoft.DBforMySQL/flexibleServers/read |
需要此权限才能获取数据库服务器信息 |
Microsoft.DBforMySQL/flexibleServers/write |
需要此权限才能将所提供的用户分配的托管标识添加到数据库服务器 |
Microsoft.DBforMySQL/flexibleServers/firewallRules/write |
需要此权限才能创建防火墙规则以防本地 IP 地址被阻止 |
Microsoft.DBforMySQL/flexibleServers/firewallRules/delete |
需要此权限才能还原服务连接器创建的防火墙规则以避免安全问题 |
Microsoft.DBforMySQL/flexibleServers/administrators/read |
需要此权限才能检查 Azure CLI 登录用户是否为数据库服务器 Microsoft Entra 管理员 |
Microsoft.DBforMySQL/flexibleServers/administrators/write |
需要此权限才能将 Azure CLI 登录用户添加为数据库服务器 Microsoft Entra 管理员 |
权限 |
操作 |
Microsoft.Sql/servers/read |
需要此权限才能获取数据库服务器信息 |
Microsoft.Sql/servers/firewallRules/write |
需要此权限才能创建防火墙规则以防本地 IP 地址被阻止 |
Microsoft.Sql/servers/firewallRules/delete |
需要此权限才能还原服务连接器创建的防火墙规则以避免安全问题 |
Microsoft.Sql/servers/administrators/read |
需要此权限才能检查 Azure CLI 登录用户是否为数据库服务器 Microsoft Entra 管理员 |
Microsoft.Sql/servers/administrators/write |
需要此权限才能将 Azure CLI 登录用户添加为数据库服务器 Microsoft Entra 管理员 |
在某些情况下,不需要权限。 例如,如果经过 Azure CLI 身份验证的用户已经是 SQL Server 上的 Active Directory 管理员,则无需具有 Microsoft.Sql/servers/administrators/write
权限。
Microsoft Entra 身份识别系统
如果收到 ERROR: AADSTS530003: Your device is required to be managed to access this resource.
错误,请向 IT 部门寻求将此设备加入 Microsoft Entra ID 的帮助。 有关详细信息,请参阅已建立 Microsoft Entra 联接的设备。
服务连接器需要访问 Microsoft Entra ID 才能获取帐户的信息以及托管服务的托管标识。 可使用以下命令检查设备是否能够访问 Microsoft Entra ID:
az ad signed-in-user show
如果无法以交互方式登录,你可能还会收到错误和 Interactive authentication is needed
。 若要解决此错误,请使用 az login
命令进行登录。
网络连接
如果数据库服务器位于虚拟网络中,请确保运行 Azure CLI 命令的环境可以访问虚拟网络中的服务器。
如果数据库服务器位于虚拟网络中,请确保运行 Azure CLI 命令的环境可以访问虚拟网络中的服务器。
如果数据库服务器不允许公共访问,请确保运行 Azure CLI 命令的环境可以通过专用终结点访问服务器。
后续步骤
有关服务连接器和无密码连接的详细信息,请参阅以下资源: