【Azure Spring Cloud】Azure Spring Cloud connect to SQL using MSI

问题描述

在Azure Spring Cloud中,通过ActiveDirectoryMSI方式来连接到SQL Service,需要如何配置呢?

 

问题分析

在SQL Service中启用Active Directory MSI认证方式,需要执行两个步骤:

1)在Auzre Spring Cloud App中分配一个Managed Identity。

 

2)在SQL Service中,使用CREATE USER 命令创建一个Contained User,并且与第一步中的Managed Identity关联。

完成以上配置后,使用JDBC + ActiveDirectoryMSI的示例代码为:

复制代码
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class AAD_MSI {
    public static void main(String[] args) throws Exception {

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("aad-managed-demo.database.chinacloudapi.cn"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database name
        ds.setAuthentication("ActiveDirectoryMSI");
        // Optional
        ds.setMSIClientId("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"); // Replace with Client ID of User-Assigned Managed Identity to be used

        try (Connection connection = ds.getConnection();
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                System.out.println("You have successfully logged on as: " + rs.getString(1));
            }
        }
    }
}
复制代码

或者使用SQLServerDataSource.setURL()来设置SQL的连接字符串

复制代码
SQLServerDataSource.setURL(): Sets the URL that is used to connect to the data source.
=================================================================================================================
jdbc:sqlserver://aad-managed-demo.database.chinacloudapi.cn:1433;
database=hsp-sql-database1-dev;
authentication=ActiveDirectoryMSI;
msiClientId=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx;
encrypt=true;
trustServerCertificate=false;
hostNameInCertificate=*.database.chinacloudapi.cn;
loginTimeout=3000;
=================================================================================================================
复制代码

 

参考资料

创建映射到 Azure AD 标识的包含的用户: https://docs.microsoft.com/zh-cn/azure/azure-sql/database/authentication-aad-configure?tabs=azure-powershell&view=azuresql#create-contained-users-mapped-to-azure-ad-identities

Connect using ActiveDirectoryMSI authentication mode:https://docs.microsoft.com/en-us/sql/connect/jdbc/connecting-using-azure-active-directory-authentication?view=sql-server-ver15#connect-using-activedirectorymsi-authentication-mode

setURL Method (SQLServerDataSource):https://docs.microsoft.com/en-us/sql/connect/jdbc/reference/seturl-method-sqlserverdatasource?view=sql-server-ver15

 

posted @   路边两盏灯  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示