Tutorial: Secure a Java web app using the Spring Boot Starter for Azure Active Directory

This article demonstrates creating a Java app with the [Spring Initializr] that uses the Spring Boot Starter for Azure Active Directory (Azure AD).

In this tutorial, you learn how to:

  • Create a Java application using the Spring Initializr
  • Configure Azure Active Directory
  • Secure the application with Spring Boot classes and annotations
  • Build and test your Java application

If you don't have an Azure subscription, create a free account before you begin.

Prerequisites

The following prerequisites are required to complete the steps in this article:

Important

Spring Boot version 2.5 or higher is required to complete the steps in this article.

Create an app using Spring Initializr

  1. Browse to https://start.spring.io/.

  2. Specify that you want to generate a Maven project with Java, enter the Group and Artifact names for your application.

  3. Add Dependencies for Spring Web, Azure Active Directory, and OAuth2 Client.

  4. At the bottom of the page, select the GENERATE button.

    Screenshot of Spring Initializr with basic options.

  5. When prompted, download the project to a path on your local computer.

Create Azure Active Directory instance

Create the Active Directory instance

If you're the administrator of an existing instance, you can skip this process.

  1. Log into https://portal.azure.com.

  2. Select All services, then Identity, and then Azure Active Directory.

  3. Enter your Organization name and your Initial domain name. Copy the full URL of your directory. You'll use the URL to add user accounts later in this tutorial. (For example: azuresampledirectory.onmicrosoft.com.)

    Copy the full URL of your directory. You'll use the URL to add user accounts later in this tutorial. (For example: azuresampledirectory.onmicrosoft.com.).

    When you've finished, select Create. It will take a few minutes to create the new resource.

    Screenshot of the Configuration section of the Azure Active Directory 'Create a tenant' screen.

  4. When complete, select the displayed link to access the new directory.

    Screenshot of 'Create a tenant' success message.

  5. Copy the Tenant ID. You'll use the ID value to configure your application.properties file later in this tutorial.

    Screenshot of Azure Active Directory tenant screen with 'Tenant ID' highlighted.

Add an application registration for your Spring Boot app

  1. From the portal menu, select App registrations, and then select Register an application.

  2. Specify your application, and then select Register.

  3. When the page for your app registration appears, copy your Application (client) ID and the Directory (tenant) ID. You'll use these values to configure your application.properties file later in this tutorial.

    Screenshot of application with 'Application (client) ID' and 'Directory (tenant) ID' highlighted.

  4. Select Certificates & secrets in the left navigation pane. Then select New client secret.

    Screenshot of application 'Certificates & secrets' screen with 'New client secret' highlighted.

  5. Add a Description and select duration in the Expires list. Select Add. The value for the key will be automatically filled in.

  6. Copy and save the value of the client secret to configure your application.properties file later in this tutorial. (You won't be able to retrieve this value later.)

    Screenshot of application with new client secret highlighted.

  7. From the main page for your app registration, select Authentication, and select Add a platform. Then select Web applications.

    Screenshot of application Authentication screen with 'Configure platforms' section showing and Web platform highlighted.

  8. Enter http://localhost:8080/login/oauth2/code/ as a new Redirect URI, and then select Configure.

    Screenshot of application Authentication screen with 'Configure Web' section showing and 'Redirect URIs' highlighted.

  9. If you've modified the pom.xml file to use an Azure AD starter version earlier than 3.0.0: under Implicit grant and hybrid flows, select ID tokens (used for implicit and hybrid flows), then select Save.

    Screenshot of application Authentication screen with 'ID tokens' selected.

Add a user account to your directory, and add that account to an appRole

  1. From the Overview page of your Active Directory, select Users, and then select New user.

  2. When the User panel is displayed, enter the User name and Name. Then select Create.

    Screenshot of 'New user' dialog.

    Note

    You need to specify your directory URL from earlier in this tutorial when you enter the user name. For example:

    test-user@azuresampledirectory.onmicrosoft.com

  3. From the main page for your app registration, select App roles, then select Create app role. Provide values for the form fields, select Do you want to enable this app role?, then select Apply.

    Screenshot of application 'App roles' screen with 'Create app role' pane showing.

  4. From the Overview page of your Azure AD directory, select Enterprise applications.

    Screenshot of Azure Active Directory 'Enterprise applications' screen.

  5. Select All applications, then select the application you added the app role to in a previous step.

    Screenshot of 'Enterprise applications' screen with 'All applications' list showing.

  6. Select Users and groups, then select Add user/group.

  7. Under Users, select None Selected. Select the user you created earlier, select Select, then select Assign. If you created more than one app role earlier, select a role.

    Screenshot of application 'Add Assignment' screen with Users pane showing.

  8. Go back to the Users panel, select your test user, and select Reset password, and copy the password. You'll use the password when you log into your application later in this tutorial.

    Screenshot of user with 'Temporary password' field highlighted.

Configure and compile your app

  1. Extract the files from the project archive you created and downloaded earlier in this tutorial into a directory.

  2. Navigate to the src/main/resources folder in your project, then open the application.properties file in a text editor.

  3. Specify the settings for your app registration using the values you created earlier. For example:

    # Enable related features.
    spring.cloud.azure.active-directory.enabled=true
    # Specifies your Active Directory ID:
    spring.cloud.azure.active-directory.profile.tenant-id=22222222-2222-2222-2222-222222222222
    # Specifies your App Registration's Application ID:
    spring.cloud.azure.active-directory.credential.client-id=11111111-1111-1111-1111-1111111111111111
    # Specifies your App Registration's secret key:
    spring.cloud.azure.active-directory.credential.client-secret=AbCdEfGhIjKlMnOpQrStUvWxYz==
    

    Where:

    Parameter Description
    spring.cloud.azure.active-directory.enabled Enable the features provided by spring-cloud-azure-starter-active-directory
    spring.cloud.azure.active-directory.profile.tenant-id Contains your Active Directory's Directory ID from earlier.
    spring.cloud.azure.active-directory.credential.client-id Contains the Application ID from your app registration that you completed earlier.
    spring.cloud.azure.active-directory.credential.client-secret Contains the Value from your app registration key that you completed earlier.
  4. Save and close the application.properties file.

  5. Create a folder named controller in the Java source folder for your application. For example: src/main/java/com/wingtiptoys/security/controller.

  6. Create a new Java file named HelloController.java in the controller folder and open it in a text editor.

  7. Enter the following code, then save and close the file:

    package com.wingtiptoys.security;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.security.access.prepost.PreAuthorize;
    
    @RestController
    public class HelloController {
         @GetMapping("Admin")
         @ResponseBody
         @PreAuthorize("hasAuthority('APPROLE_Admin')")
         public String Admin() {
             return "Admin message";
         }
    }
    

Build and test your app

  1. Open a command prompt and change directory to the folder where your app's pom.xml file is located.

  2. Build your Spring Boot application with Maven and run it. For example:

    mvn clean package
    mvn spring-boot:run
    

    Screenshot of Maven build output.

  3. After your application is built and started by Maven, open http://localhost:8080/Admin in a web browser. You should be prompted for a user name and password.

    Screenshot of application 'Sign in' dialog.

    Note

    You may be prompted to change your password if this is the first login for a new user account.

    Screenshot of application 'Update your password' dialog.

  4. After you've logged in successfully, you should see the sample "Admin message" text from the controller.

    Screenshot of application admin message.

Summary

In this tutorial, you created a new Java web application using the Azure Active Directory starter, configured a new Azure AD tenant, registered a new application in the tenant, and then configured your application to use the Spring annotations and classes to protect the web app.

See also

Next steps

To learn more about Spring and Azure, continue to the Spring on Azure documentation center.