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:
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];
Connection string for JDBC driver.
I tested locally and got a success. Here are my steps for your reference:
Here, I will use function app.

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



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:

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