问题
I am trying to use my AD account to connect to the Azure SQL using Java 8, JDBC Driver, and my accessToken.
When I use Data Studio using my AD Account, I can connect successfully to the Azure SQL DB.
But when I use my Java Program then it gives me this error:
Request processing failed; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''
My code abstract:
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);
}
}
回答1:
After discussion in comments, we found out that we needed to change the scope used when getting the access token.
"User.Read.All" was specified, which is the short form "https://graph.microsoft.com/User.Read.All"
.
This means a Microsoft Graph API access token is returned, which won't work with Azure SQL DB.
Changing the scope to "https://database.windows.net/.default"
resolved the issue.
This gets an access token for Azure SQL DB with the static permissions that the app registration has on Azure SQL DB.
Documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent
来源:https://stackoverflow.com/questions/65173552/login-failed-for-user-token-identified-principal-but-works-in-data-studio