Search code examples
springjdbcazure-active-directoryadal4j

How do I connect to Azure SQL DB with AD password using JDBC configuration?


I am trying to connect from my Spring Boot (2.0.1) Web Application to an Azure SQL DB using Azure AD (with the Application as the DB user) but cannot seem to connect the dots.

I followed the steps for Connecting using Azure AD Auth. However, I get a failed login.

I'm assuming that's because without setting the 'authentication' property in the JDBC url, it's just authenticating against the database directly (user created using CREATE USER <> FROM EXTERNAL PROVIDER from instructions)?

Is there a way to configure the spring datasource/jdbc libraries to use the proper Azure AD authentication (adal4j-1.6.3) while connecting? The example does this in code, but I'm having trouble finding the proper configurations.

I tried using 'authentication=ActiveDirectoryPassword', but kept getting a 'AADSTS50034: The user account does not exist in the directory' error.

spring.datasource.url="jdbc:sqlserver://myServer.database.windows.net:1433;database=myDB;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;applicationName=myApp;"

spring.datasource.username: <user>
spring.datasource.accessToken: <key>

The bigger goal is to secure my database access to specific apps. I had added my app as a Reader on my server and ideally would authenticate as that application to track usage/analytics/etc from that app.

I apologize if this is way off, I'm new to Azure and Oauth. Thanks.


Solution

  • There is no way to configure Spring to use an application Id + key from Azure AD in place of username/password when connecting to Azure SQL DB. The only way I found was to modify code and create a @Bean method that returned an SQLServerDataSource where I manually retrieve a Client Credential access token and pass that into the data source.

    Connecting using an access token - shows how to retrieve token and set on data source

    Creating a custom Data Source - shows how to use Spring to create and use custom data source

    Also be aware of token management (see my other question).