You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否使用Azure用户分配托管标识通过R2DBC驱动连接Azure SQL DB?

用用户分配托管标识实现Spring Boot WebFlux应用无密码连接Azure SQL DB

可以通过用户分配托管标识实现无密码连接,虽然r2dbc-mssql驱动本身没有直接集成Azure AD认证,但借助Azure Identity库获取访问令牌,结合R2DBC连接配置就能实现。以下是具体步骤:

1. 前置准备

  • 给你的Azure Container App分配用户分配托管标识,记录该标识的Client ID。
  • 为这个托管标识授予Azure SQL DB的权限:
    • 在Azure SQL DB的权限设置中添加该托管标识,分配合适的数据库角色(如db_datareader、db_datawriter,测试阶段可临时用db_owner)。
    • 确保Azure SQL DB已启用Azure AD认证,并设置了Azure AD管理员。

2. 添加依赖

在Maven中引入必要依赖:

<!-- Spring Boot R2DBC starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<!-- R2DBC SQL Server驱动 -->
<dependency>
    <groupId>io.r2dbc</groupId>
    <artifactId>r2dbc-mssql</artifactId>
</dependency>
<!-- Azure Identity库,用于获取托管标识令牌 -->
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.12.0</version> <!-- 使用最新稳定版 -->
</dependency>

3. 配置R2DBC连接与令牌获取

创建配置类,通过用户分配托管标识获取Azure SQL的访问令牌,再构建R2DBC连接工厂:

import com.azure.identity.DefaultAzureCredential;
import com.azure.identity.DefaultAzureCredentialBuilder;
import io.r2dbc.mssql.MssqlConnectionConfiguration;
import io.r2dbc.mssql.MssqlConnectionFactory;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class R2dbcAzureSqlConfig {

    @Bean
    public ConnectionFactory connectionFactory() {
        // 初始化Azure凭据,指定用户分配托管标识的Client ID
        DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
                .managedIdentityClientId("你的用户分配托管标识Client ID")
                .build();

        // 获取Azure SQL的访问令牌,资源固定为https://database.windows.net/
        String accessToken = credential.getToken(
                new com.azure.core.credential.TokenRequestContext()
                        .addScopes("https://database.windows.net/.default")
        ).block().getToken();

        // 构建SQL Server连接配置
        MssqlConnectionConfiguration config = MssqlConnectionConfiguration.builder()
                .host("你的SQL服务器名称.database.windows.net")
                .database("你的数据库名称")
                .username("任意非空值") // 令牌认证时该字段会被忽略,但不能为空
                .password(accessToken)
                .build();

        return new MssqlConnectionFactory(config);
    }
}

注意事项:

  • 令牌存在过期时间(通常约1小时),建议实现令牌自动刷新逻辑,比如在每次获取数据库连接时动态获取最新令牌,避免因令牌过期导致连接失败。
  • 如果使用系统分配托管标识,只需移除managedIdentityClientId配置即可。

4. 测试连接

创建简单的Repository和Controller,验证数据库读写操作是否正常,确认无密码连接生效。

内容的提问来源于stack exchange,提问作者Marcin Nowrot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:46:16