3

I want to Access the Azure SQL Database using App service API(Java) with MSI (Managed Service Identity) authentication.

I am trying to find out the how to connect Azure sql with MSI from Azure App service for Java.

Here is the connection string I am using.

jdbc:sqlserver://mysqldb.database.windows.net:1433;database=TestDB;Authentication=ActiveDirectoryMsi;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;

Here is the steps I used:

  1. Create AAD group
  2. Add Azure web app'S MI(Managed Identity) to this AAD group
  3. Add this group as Active Directory admin to Azure SQL Server
  4. Create user and give roles for this group.

    CREATE USER [myAADgroup] FROM EXTERNAL PROVIDER;
    ALTER ROLE db_datareader ADD MEMBER [myAADgroup];
    ALTER ROLE db_datawriter ADD MEMBER [myAADgroup];
    ALTER ROLE db_ddladmin ADD MEMBER [myAADgroup];
    
  5. Connection string for JDBC driver.

TT.
  • 15,774
  • 6
  • 47
  • 88
Ammanuel g
  • 151
  • 2
  • 4
  • Have you added your app service in SQL database using Access Control? Ref: https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/tutorial-windows-vm-access-sql [This ref is for VM but same way you can give access for your app service] – Anish K Sep 10 '19 at 17:22
  • Yes, I did. I included the steps I followed. – Ammanuel g Sep 10 '19 at 18:48
  • @Ammanuelg Did you try this tutorial [Connecting using ActiveDirectoryMSI authentication mode](https://learn.microsoft.com/en-us/sql/connect/jdbc/connecting-using-azure-active-directory-authentication?view=sql-server-2017#connecting-using-activedirectorymsi-authentication-mode)? – Leon Yue Sep 11 '19 at 01:15
  • I tried the code in the link where @LeonYue recommend but I am getting the same issue. – Ammanuel g Sep 11 '19 at 17:51
  • Have you find a solution yet? I'm trying the same but getting the same error – Joost Luijben May 16 '20 at 00:57
  • The issue was the latest version of mssql-jdbc libary(6.x) at that time was not supporting the MSI authentication. Microsoft fixed the issue on their 7.0.x version and it is working fine now. The latest version of mssql-jdbc libary is supporting MSI authentication. – Ammanuel g May 18 '20 at 04:13
  • @Ammanuelg I've done the exact same as in Jack's answer, but I'm still getting the same error. I'm using the 7.2.1.jre11 version of the mssql-jdbc driver. I've tried 8.2.2.jre11 as well but this didn't work either – Joost Luijben May 18 '20 at 22:42
  • @JoostLuijben, Sorry to hear that. There might be firewall around the Azure SQL including the VNet. I might assist you if you share the code snippte, the Azure SQL Server and db configuration including the networking(VNet, subnet, ...). – Ammanuel g May 23 '20 at 05:45

2 Answers2

3

I tested locally and got a success. Here are my steps for your reference:

1. Enable the managed identity for your web app, or function app, or VM

Here, I will use function app.

enter image description here

and then set the status to on and save. And you will get an object ID.

enter image description here

2. Create an Azure AD group, and add the identity as a member

enter image description here

3. Configure the Azure SQL Server on portal

enter image description here

4. Connect to database

Here, I deploy my app to a function app. The sample:

public class Function {

    @FunctionName("HttpTrigger-Java")
    public HttpResponseMessage run(@HttpTrigger(name = "req", methods = {
            HttpMethod.GET }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {

        String result = "";

        SQLServerDataSource ds = new SQLServerDataSource();
        ds.setServerName("jacksqldemo.database.windows.net"); // Replace with your server name
        ds.setDatabaseName("sqldemo"); // Replace with your database name
        ds.setAuthentication("ActiveDirectoryMSI");

        try (Connection connection = ds.getConnection(); 
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
            if (rs.next()) {
                String s = rs.getString(1);
                context.getLogger().info("You have successfully logged on as: " + s);
                result += "You have successfully logged on as: " + s;
            }
        }catch(Exception e){
            context.getLogger().log(Level.WARNING, e.getMessage(),e);
        }
        return request.createResponseBuilder(HttpStatus.OK).body(result).build();
    }
}

Finally, I can connect to Azure SQL:

enter image description here

Jack Jia
  • 5,268
  • 1
  • 12
  • 14
  • Thanks for details steps. I am using Azure web app instead of Azure function. Anyway I will try it. – Ammanuel g Sep 16 '19 at 19:59
  • What needs to be done for on-prem machines to achieve the same. Here I have posted my question I'll be very thankful if you @Jack jia or someone can answer Here is the slack post: https://stackoverflow.com/questions/62513972/onprem-machines-to-azure-active-directory-so-we-can-access-activedirectorymsi-au – Ajay Kumar Jaiswal Jun 22 '20 at 12:16
2

I was working with Microsoft teams and they confirm that the JDBC library(mssql-jdbc) is the issue and they are working on this fix. I have got a change to test their preview JDBC library and it is working as expected. So the next release of the JDBC library will resolve it.

Ammanuel g
  • 151
  • 2
  • 4