【发布时间】:2021-01-20 06:11:42
【问题描述】:
如何使用 JDBC 连接字符串中的访问令牌连接到 Azure SQL DW?
【问题讨论】:
-
嗨@Whiplash,欢迎来到堆栈溢出!如果我的回答对您有帮助,您可以接受它作为答案(单击答案旁边的复选标记,将其从灰色切换为已填充。)。这对其他社区成员可能是有益的。谢谢。
标签: sql azure jdbc access-token data-warehouse
如何使用 JDBC 连接字符串中的访问令牌连接到 Azure SQL DW?
【问题讨论】:
标签: sql azure jdbc access-token data-warehouse
请参考本 Azure 教程:Connecting using access token:
下面的示例包含一个简单的 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。
【讨论】: