Migrating Java Applications to Azure App Service (Part 1 — DataSources and MSI Credentials)

Running on the cloud is not only for cool new applications following 12-factor principles and coded to be cloud-native. Many applications could be converted to be cloud-ready with minimal adjustments in order to run in a cloud environment. In this series, we will demonstrate how to address the most common migration items in legacy Spring applications — handling JNDI, and credentials, externalizing configuration, remote debugging, logging, and monitoring.

This article demonstrates how to migrate Java Spring/Hibernate applications using JNDI settings to cloud environment, externalize configuration, and how to keep credentials out of code by using Azure Managed Service Identity.

How Azure App Service Hosts Java

Azure App Service supports multiple application runtimes: Java, Node, Python, .NET and others. On Azure App Service Windows service, HTTP requests reach IIS on an App Server worker instance and are processed by theHttpPlatformHandlermodule. This module is described in detail in Microsoft docs. The role of HttpPlatformHandleris to start and manage an HTTP listener process on the localhost and proxy traffic to it. HTTP listener could be any process handling web requests. For a Java application we will configure Tomcat to process the requests.

Azure App Service has necessary Java tools such as the JDK and Tomcat application server and configuration files installed and managed on the host. For example, managed Tomcat files are installed under D:\Program Files (x86)\apache-tomcat-x.x.xx\conf. Example of web.config that uses Tomcat as runtime:

Spring/Hibernate JNDI DataSources for Azure SQL server

Majority of the legacy Spring Applications use Hibernate to implement data access. Hibernate is using container-managed JNDI DataSources in Tomcat application Server and referencing them as resources in descriptors.

There are few options to configure JNDI for the web application running under Tomcat (Tomcat JNDI):

  • Application context.xml — located in app META-INF/context.xml - define Resource element in the context file and container will take care of loading and configuring it.
  • Server.xml — Global, shared by applications, defined in tomcat/conf/server.xml
  • Server.xml and context.xml — defining Datasource globally and including ResourceLink in application context.xml

When deploying Java application on Azure App Service, you can customize out-of-the-box managed Tomcat server.xml, but is not recommended as it will create a snowflake deployment. The right way is to define JNDI Datasource on the Application level.To do that add file META-INF/context.xml to the application.

The example used in this article and this file is added to main/webapp/META-INF/context.xml and is providing connection to Azure SQL server:

<Context> 
<Resource auth="Container" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxActive="8" maxIdle="4"
name="jdbc/tutorialDS"
type="javax.sql.DataSource"
url="${SQLDB_URL}" />
</Context>

To avoid putting credentials and environment specifics inside the application and in source control, the actual URL and username/password are referenced by environment variable which is set during application deployment as described in the section below.

Include SQL Server Driver libraries in pom.xml :

<dependency> 
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre7</version>
</dependency>

and update Hibernate to use SQL Server dialect in resources\META-INF\persistence.xml:

<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />

Spring Application Deployment

There are a number of options to create and deploy a web app in Azure App Service. We will use a portal for simplicity. In Azure portal create WebApp + SQL and configure Tomcat and JDBC settings

Copy Database connection string from Azure SQL JDBC tab:

Add Azure SQL connection string to AppService/ApplicationSettings, so that it will be available to the Java application as an environment variable to be used in context.xml

To make the environment variable available to Tomcat process on startup it should be passed as a parameter in JAVA_OPTS . As a result of the sample setting above variable SQLDB_URL will be available to the Tomcat application and bound in Datasource definition in context.xml.

Build and deploy the application using the Maven plugin or FTP. To use the Maven plugin:

  • Setup authentication in .m2/settings.xml as described in this article and reference it as shown in lines 6-8 below.
  • Add following definition in pom.xml (pointing to server authentication) defining all the app service settings:
  • To build and deploy run:
mvn clean package mvn azure-webapp:deploy
  • war file will be deployed to d:/home/site/wwwroot/webapps/tutorial-hibernate.war

Example output:

[INFO] 
--- azure-webapp-maven-plugin:0.2.0:deploy (default-cli) @ tutorial-hibernate-jpa
--- AI: INFO 25-03-2018 19:31, 1: Configuration file has been successfully found as resource
[INFO] Start deploying to Web App testjavajndi...
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: 462a8a7f-c2ec-40c8-a43b-80be705225b8] Instance discovery was successful [INFO] Updating target Web App... [INFO] Copying 1 resource to C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi\webapps
[INFO] Starting uploading directory: C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi --> /site/wwwroot
[INFO] [DIR] C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi --> /site/wwwroot [INFO] ..[DIR] C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi\webapps --> /site/wwwroot/webapps
[INFO] ....[FILE] C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi\webapps\tutorial-hibernate-jpa.war --> /site/wwwroot/webapps [INFO] ...........Reply Message : 226 Transfer complete. [INFO] Finished uploading directory: C:\projects\tutorial-hibernate-jpa\target\azure-webapps\testjavajndi --> /site/wwwroot [INFO] Successfully uploaded files to FTP server: waws-prod-yt1-005.ftp.azurewebsites.windows.net [INFO] Successfully deployed Web App at https://testjavajndi.azurewebsites.net

Navigate https://appname.azurewebsites.net/tutorial-hibernate-jpa/create-user.html to test the app.

Get Credentials Out of the code — Managed Service Identity

The solution above showed how to deploy a Java Spring application and connect it to Azure SQL DataSource. It requires managing credentials, although they are externalizing from the code but still need to be managed and entered in application settings. This problem is now solved through the magic of Azure AD and MSI (Managed Service Identity) More details are available here.

In summary, Managed Service Identity is Azure AD identity assigned to the service and fully managed by Azure. Once enabled on App Service, it makes local endpoint available to the Web Applications to fetch the Azure AD token (supported by injected credentials). This token could be used to authenticate to other services that support Azure AD authentication, such as Azure KeyVault and Azure SQL.

At the time of the writing MSI is not natively supported by JDBC driver, but driver does support Azure AD authentication mechanisms described in Connect using Azure AD authentication and the approach we will be using to pass an MSI issued token is accessToken that could be passed to driver when establishing connection:

accessToken: Use this property to connect to a SQL database using an access token. accessToken can only be set using the Properties parameter of the getConnection() method in the DriverManager class. It can’t be used in the connection URL.

Steps described below are demonstating how to use MSI accessToken with JDBC connections in Spring applications. Traditionally all Spring application are using connection pools for the DB connections and as such we need to be able to refresh the token. (By default MSI token TTL is 8 hours). To enable token refresh functionality we have created a library that leverages Tomcat pool and DBCP pool extensibility points to demonstrate how connections aquire refreshed tokens.

Enable Managed Service Identity in App Service

Steps to enable MSI in AppService:

  • Assign MSI identity to Azure App Service — Azure will assign and inject AD credentials
az webapp identity assign --resource-group <resource_group> --name <app_service_name> 
az ad sp show --id <id_created_above>
  • Grant MSI identity access to Azure SQL DB (it could be assigned to AD group or admin user)
az sql server ad-admin create --resource-group <resource_group> --server-name <sql_server_name> --display-name <admin_account_name> --object-id <id_created_above>
  • Verify using Kudu console that MSI_ENDPOINT and MSI_SECRET variables are injected by Azure
At the time of the writing, SQL Server JDBC driver does not natively support MSI yet (the work is in progress by Microsoft engineers), but luckily, the driver supports Azure AD authentication using accessToken as outlined in JDBC driver docs.

MSI Connection Library

To enable getting an MSI token from the local endpoint and passing it to Azure SQL connection, I have created a library that extends the common Java Database Connection pooling libraries (Apache DBCP and Tomcat JDBC) and injects accessToken in getting connections. Library is available in Github and is published on Maven Central.

Once the application tries to get a connection from the pool, the library will invoke MSI Endpoint to get the token and inject it in URL to provide authentication for the connection.

There are currently two ways to use the library, using Tomcat JDBC pool that provides an extensible way to intercept calls in lifecycle of connection management, and using Tomcat default Apache DBCP pool and Spring AOP to intercept the calls. A lot of legacy applications are dependent on DBCP library and if the bean definition xml file is accessible, you could use the solution using Apache DBCP outlined below. If DBCP usage is not critical for the application, switch pooling mechanism to Tomcat JDBC and the changes will be minimal.

Enabling MSI token functionality as per 12-factor principles is done using environment settings:

  • Environment variable: JDBC_MSI_ENABLE=true, set it in ApplicationSettings for Azure WebApp
  • jdbcURL flag: to set it add in jdbc connection string msiEnable=true. E.g jdbc:sqlserver://server.database.windows.net:1433;database=db;msiEnable=true;...

Tomcat JDBC Pool with MSI

Tomcat JDBC pool provides an extensibility to change connection behavior using JDBCInterceptor interface. MSI library provides custom JDBCInterceptor that obtains, caches and refreshes the token for the connection. To use it:

  • Add required libraries to the application pom.xml:
<dependency> 
<groupId>com.microsoft.sqlserver.msi</groupId>
<artifactId>msi-mssql-jdbc</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre7</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>3.1.2</version>
</dependency>
  • Define DataSource with MSI Interceptor and Tomcat pool DataSourceFactory in main/webapp/META-INF/context.xml as shown in line 8 and 9:
  • Make sure remove username/password fromSQLDB_URLand addJDBC_MSI_ENABLE variable:

Build and deploy the application and it will establish a connection without having credentials in code or settings.

Apache DBCP Pool with MSI

Apache DBCP pool does not have a convenient way to override the connection behavior. The easiest way to inject the new functionality to the connection is to use Spring AOP Aspect. MSI library provides Aspect that proxies execution of the pool method org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection()

It obtains, refreshes, caches and injects token in the connection. To use this approach:

Add required libraries to pom.xml

<dependency> 
<groupId>com.microsoft.sqlserver.msi</groupId>
<artifactId>msi-mssql-jdbc</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.4.0.jre7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
<version>3.1.2</version>
</dependency>

Add Aspect bean to Spring bean definitions in -application-context.xml or *-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" ... http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd "> 
<aop:aspectj-autoproxy /> 
<bean id="msiAspect" class="com.microsoft.sqlserver.msi.MsiTokenAspect"/>
</beans>

Define Datasource and DBCP pool DataSourceFactory in main/webapp/META-INF/context.xml

<Context> 
<Resource
auth="Container" driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" maxActive="8" maxIdle="4"
name="jdbc/tutorialDS"
type="javax.sql.DataSource" url="${SQLDB_URL}" factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" /> </Context>

Make sure to remove the username/password from SQLDB_URL and add JDBC_MSI_ENABLE variable in ApplicationSettings.

Build and deploy the application and it will establish a connection without having credentials in code or settings.

Summary

In this article, we have demonstrated how to take legacy Java Spring application and apply one of 12 factor principles by extracting configuration from code and providing it in environment variables. We have also shown how to get credentials out of the code by using Azure Managed Service identity.


Originally published at dzone.com.