用户“<token-identified principal>”登录失败但在 Data Studio 中有效
Login failed for user '<token-identified principal>' but works in Data Studio
我正在尝试使用我的 AD 帐户通过 Java 8、JDBC 驱动程序和我的 accessToken 连接到 Azure SQL。
当我使用我的 AD 帐户使用 Data Studio 时,我可以成功连接到 Azure SQL 数据库。
但是当我使用我的 Java 程序时它给我这个错误:
请求处理失败;嵌套异常是 com.microsoft.sqlserver.jdbc.SQLServerException:用户 ''
登录失败
我的代码摘要:
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("NAME.database.windows.net");
ds.setDatabaseName("db-name");
ds.setAccessToken(accessToken);
ds.setEncrypt(true);
ds.setTrustServerCertificate(true);
try (Connection connection = ds.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
if (rs.next()) {
System.out.println("dbResults => You have successfully logged on as: " + rs.getString(1));
res = rs.getString(1);
}
}
经过评论讨论,我们发现我们需要更改获取访问令牌时使用的范围。
指定了“User.Read.All”,这是 "https://graph.microsoft.com/User.Read.All"
的缩写形式。
这意味着将返回一个 Microsoft Graph API 访问令牌,它不适用于 Azure SQL 数据库。
将范围更改为 "https://database.windows.net/.default"
解决了该问题。
这将获取 Azure SQL DB 的访问令牌,该令牌具有应用程序注册在 Azure SQL DB 上具有的静态权限。
文档:https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent
我正在尝试使用我的 AD 帐户通过 Java 8、JDBC 驱动程序和我的 accessToken 连接到 Azure SQL。
当我使用我的 AD 帐户使用 Data Studio 时,我可以成功连接到 Azure SQL 数据库。
但是当我使用我的 Java 程序时它给我这个错误:
请求处理失败;嵌套异常是 com.microsoft.sqlserver.jdbc.SQLServerException:用户 ''
登录失败我的代码摘要:
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("NAME.database.windows.net");
ds.setDatabaseName("db-name");
ds.setAccessToken(accessToken);
ds.setEncrypt(true);
ds.setTrustServerCertificate(true);
try (Connection connection = ds.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
if (rs.next()) {
System.out.println("dbResults => You have successfully logged on as: " + rs.getString(1));
res = rs.getString(1);
}
}
经过评论讨论,我们发现我们需要更改获取访问令牌时使用的范围。
指定了“User.Read.All”,这是 "https://graph.microsoft.com/User.Read.All"
的缩写形式。
这意味着将返回一个 Microsoft Graph API 访问令牌,它不适用于 Azure SQL 数据库。
将范围更改为 "https://database.windows.net/.default"
解决了该问题。
这将获取 Azure SQL DB 的访问令牌,该令牌具有应用程序注册在 Azure SQL DB 上具有的静态权限。
文档:https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent