在application.properties中使用AD服务主体设置Spring Data JPA

c6ubokkw  于 12个月前  发布在  Spring
关注(0)|答案(1)|浏览(248)

根据Azure中的文档:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

public class AADServicePrincipal {
    public static void main(String[] args) throws Exception{
        String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your AAD service principal ID.
        String principalSecret = "..."; // Replace with your AAD principal secret.

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("demo"); // Replace with your database
        ds.setAuthentication("ActiveDirectoryServicePrincipal");
        ds.setAADSecurePrincipalId(principalId);
        ds.setAADSecurePrincipalSecret(principalSecret);

        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));
            }
        }
    }
}

字符串
我们可以使用它来创建一个可以通过AD服务主体连接到SQL Server的数据源,并将其作为Bean插入,我相信是:

@Bean
@Primary
DataSource dataSource() throws SQLException {
    String principalId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your AAD service principal ID.
    String principalSecret = "..."; // Replace with your AAD principal secret.
    
    SQLServerDataSource ds = new SQLServerDataSource();
    ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name
    ds.setDatabaseName("demo"); // Replace with your database
    ds.setAuthentication("ActiveDirectoryServicePrincipal");
    ds.setAADSecurePrincipalId(principalId);
    ds.setAADSecurePrincipalSecret(principalSecret);
    return ds;
}


但我想问的是--我们能通过YAML/application.properties配置整个程序,让它自动配置数据JPA吗?如果不能,上述过程能正常工作吗?

ki0zmccv

ki0zmccv1#

下面的配置对我有用。

spring:
  datasource:
    url: jdbc:sqlserver://<host>:<port>;database=<database name>;authentication=ActiveDirectoryServicePrincipal;
    username: <your AAD service principal ID>
    password: <your AAD principal secret>

字符串
根据document,我的配置可以从JDBC Driver 10.2开始使用。

相关问题