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:

  • Project: Gradle
  • Project Metadata Artifact: oauth2-demo-gradle
  • Dependencies: Web, Security, Azure Active Directory

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’re 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/. You should receive a request to log in to Azure services. Log in as the user created in the step above, and you should see the following:

Assuming the general API is working, now confirm that the secure endpoint is also working. This endpoint will verify the logged in user is part of a verified group.

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

Leave a Reply

Your email address will not be published. Required fields are marked *