【问题标题】:JDBC connection string for SQL DWSQL DW 的 JDBC 连接字符串
【发布时间】:2021-01-20 06:11:42
【问题描述】:

如何使用 JDBC 连接字符串中的访问令牌连接到 Azure SQL DW?

【问题讨论】:

  • 嗨@Whiplash,欢迎来到堆栈溢出!如果我的回答对您有帮助,您可以接受它作为答案(单击答案旁边的复选标记,将其从灰色切换为已填充。)。这对其他社区成员可能是有益的。谢谢。

标签: sql azure jdbc access-token data-warehouse


【解决方案1】:

请参考本 Azure 教程:Connecting using access token:

  • 应用程序/服务可以从 Azure 检索访问令牌 Active Directory 并使用它连接到 Azure SQL 数据库/数据 仓库。

下面的示例包含一个简单的 Java 应用程序,它使用基于访问令牌的身份验证连接到 Azure SQL 数据库/数据仓库。

代码示例:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;

// The azure-activedirectory-library-for-java is needed to retrieve the access token from the AD.
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;

public class AADTokenBased {

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

        // Retrieve the access token from the AD.
        String spn = "https://database.windows.net/";
        String stsurl = "https://login.microsoftonline.com/..."; // Replace with your STS URL.
        String clientId = "1846943b-ad04-4808-aa13-4702d908b5c1"; // Replace with your client ID.
        String clientSecret = "..."; // Replace with your client secret.

        AuthenticationContext context = new AuthenticationContext(stsurl, false, Executors.newFixedThreadPool(1));
        ClientCredential cred = new ClientCredential(clientId, clientSecret);

        Future<AuthenticationResult> future = context.acquireToken(spn, cred, null);
        String accessToken = future.get().getAccessToken();

        System.out.println("Access Token: " + accessToken);

        // Connect with the access token.
        SQLServerDataSource ds = new SQLServerDataSource();

        ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name.
        ds.setDatabaseName("demo"); // Replace with your database name.
        ds.setAccessToken(accessToken);

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

HTH。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2019-08-23
    • 2017-09-05
    • 1970-01-01
    • 2014-04-27
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多