Create a Java Web App with Spring Boot Starter, Gradle, and Azure Active Directory

Working on a project that would eventually use Azure Active Directory for authentication, I wanted to use Microsoft’s guide to get started with an app that could authenticate. However, the guide is written using Maven – and in our case, we are using Gradle for builds across the ecosystem.

I was able to mostly follow the guide provided, but ran into a gotcha – involving having to add a fixed dependency to get the system working. In addition, I added a secondary API endpoint to allow for testing both with and without group authentication.

To get started, you’ll need the following:

Create an App With Spring Initializr

To get started, create an app at https://start.spring.io/ with the following information:

After clicking ‘Generate Project’, a ZIP file will be created. Extract this file to someone on your local machine, as you’ll be configuring it later.

Set Up Azure Active Directory

After the app is created, the next step is setting up Azure Active Directory for authentication. Follow the Create Azure Active Directory instance section, taking note of the App Registration information provided.

Once you get to the section involving configuration of the app, come back to this guide – you’ll make specific changes to make the testing experience both compatible with Gradle and a little more user-friendly.

Configure and Compile the App

Once Azure Active Directory is configured, open your Java IDE and import the build.gradle file as a project. After that’s done, there are a few files to configure/create.

Add the following dependencies into the build.gradle file (notice the third dependency, if this one is not added, you’ll run into an exception when testing):

Edit /src/main/resources/application.properties to look like the following:

Create a file called /controller/HelloController.java and add the following:

Create another file called security/WebSecurityConfig.java and add the following:

Build and Verify App

Now that the configuration is complete, next step is building and testing. Run the following Gradle commands (easy way to do this is through the IDE):

You should end up with a log like the following:

Once this is confirmed, access http://localhost:8080/version. You should be able to access without logging into Azure.

Next, check http://localhost:8080/secure. You should receive a request to log in to Azure services. Log in as the user created in the step above, and you should be able to get a Hello World message.

Finally, confirm that the /secureByGroup endpoint is also working. This endpoint will verify the logged in user is part of a verified group.

This code can be found at

Reference: https://docs.microsoft.com/en-us/java/azure/spring-framework/configure-spring-boot-starter-java-app-with-azure-active-directory?view=azure-java-stable

]]>