Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login failed for user '<token-identified principal>' but works in Data Studio

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);
            }
        }
like image 779
rohit12sh Avatar asked Oct 16 '25 12:10

rohit12sh


1 Answers

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://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent

like image 152
juunas Avatar answered Oct 18 '25 04:10

juunas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!