Azure AD Integration in Spring Boot Application

Pradeep Maiya
Version 1
Published in
7 min readJun 7, 2022

This document explains how to enable scope and role-based authorization using Azure Active Directory as Identity Provider/Authentication Server (IdP) whereas Spring boot will act as a resource server that will validate the access token generated by the IdP and passed by the client application (Angular UI).

Prerequisites needed before implementing this:
1. Azure subscription
2. Java JDK 8 or higher version (installed locally)
3. Apache Maven 3 or higher (installed locally)
4. An application should be registered under Azure portal > Azure Active Directory > App registration (will be discussed later in the documentation)

What is Azure AD?

Azure Active Directory (Azure AD) is a cloud-based identity and access management service. This service helps your employees access external resources, such as Microsoft 365, the Azure portal, and thousands of other SaaS applications. Azure Active Directory also allows them to access internal resources like apps on your corporate intranet network and any cloud apps developed for your own organization.

With the help of Azure AD, this article will discuss how to secure a Spring Boot Application with the use of scope-based authentication. This will use Azure AD as an authentication server & Spring Boot Application acts as a resource server. Spring boot will validate the token received from the client application which is the Angular APP.

How does authorization code flow work?

Token flow happens when a user logs into the system.

User-Agent: Is the end-user who accesses the application

Client Application: An application that uses tokens from the authorization server to access the resource server on behalf of the resource owner. It orchestrates the process of obtaining and renewing these tokens

Authorization Server: The server which validates your credentials. Generates tokens to registered clients, in our case it’s Azure AD

Resource Server: It’s a server where our APIs reside, in our case, it’s a Spring Boot Application

The resource server will be having four main components:

  1. API — a REST controller to expose the resource
  2. Security Configuration — a class to define access control for the protected resource that the API exposes
  3. application.properties — a config file to declare properties, including information about the authorization server
  4. pom.xml — all dependencies which are required to associate Java Spring boot application as a resource server

How to set up an Authorization Server?

To set up an Azure AD tenant we need to have one Azure subscription in place. If you already have a tenant, then follow the following steps to configure the App registration:

  1. Navigate to the search bar in the Azure portal and search for “Azure Active Directory”
  2. Click on “App registrations” and click on the “New registration” option on the top
  3. Provide a unique name for the registration that defines what does your application does and click on the “Register” button
  4. Now let’s add different scopes required for accessing APIs Initially, click on the “Set” button to set “Application ID” which will be the base URL used in Scopes. Then click on the “Add a scope” button to add new scope > provide “Scope name” (which will be used in the backend to access scope), add consents as “Admins & users”, provide “Admin consent display name” and “Admin consent description” details and click on “Add scope”
  5. That’s it, this is pretty much everything that you need to configure the resource server, which will validate the access token generated by a client application (angular application) with the help of the Authorization server (Azure active directory)

How to set up a Resource Server?

The role of the Resource server is to validate the token generated after a successful login in the Client Application. It also provides scope/role-based authorized access to the APIs which are hosted on the server.

Dependencies to be added in the pom.xml file

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-oauth2-resource-server</artifactId><version>4.0.0</version></dependency><dependency><groupId>com.azure.spring</groupId><artifactId>azure-spring-boot-starter-active-directory</artifactId><version>3.14.0</version></dependency><dependency><groupId>com.azure.spring</groupId><artifactId>spring-cloud-azure-starter-active-directory</artifactId> <version>4.0.0</version></dependency>

Once we add the above dependency, let's create a new configuration class that will specify the security configuration for the API to secure endpoints.

The AADResourceServerWebSecurityConfigurerAdapter base class contains the necessary web security configuration for the resource server.

The DefaultAADResourceServerWebSecurityConfigurerAdapter class is configured automatically if you don’t provide a configuration.
To provide a configuration, extend the AADResourceServerWebSecurityConfigurerAdapter class and call super.configure(http) in the configure(HttpSecurity http) function.

import com.azure.spring.aad.webapi.AADResourceServerWebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends AADResourceServerWebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
}
}

The above security config.class requires that any calls made to the API endpoints in the Spring Boot Application have to be authenticated.

Scopes are typically used when an external application wants to gain access to the user’s data via an exposed API. They determine what the client application can do. Since APIs are secured under particular scopes, only users with these particular scopes can access those respective APIs.

To secure APIs using a scope, add the below the line on top of every controller method signature.

@PreAuthorize("hasAuthority('SCOPE_{SCOPE_NAME}')")Public String METHOD_NAME(){----------------------------------------------------------------}

{SCOPE_NAME} >> replace this with the actual scope name which is created under “Expose an API” under “App registration”.

Roles are typically used when an external application needs to make calls to an API without a user present, in these cases the applications are assigned roles to define which endpoints of the API the particular application has access to.

To secure APIs using a role, add the below line on top of every controller method signature.

@PreAuthorize("hasAuthority(APPROLE_{ROLE_NAME}')")Public String METHOD_NAME(){----------------------------------------------------------------}

{ROLE_NAME} >> replace this with the actual scope name which is created under “Expose an API” under “App registration”.

One last thing we need to add is properties that will say which App registration our app is associated with, meaning we need to add “client-id” and “scope” details in the application.properties file. This is used to associate the current Spring Boot Application with that App registration.

spring.cloud.azure.active-directory.enabled=truespring.cloud.azure.active-directory.credential.client-id=CLIENT_IDspring.cloud.azure.active-directory.app-id-uri=APPLICATION_ID_URL

Where “CLIENT_ID” is the “Application (client) ID” present under the “Overview” section in App registration, “APPLICATION_ID_URL” is the “Application ID URI” present under the “Expose an API” section under App registration.

That’s it, those are the required steps to be performed to make Spring Boot Application a resource server. The Azure active directory will act as an Authorization server which will be held responsible for providing access tokens for requests made from the angular client application.

How to Test?

To test this, we will be using the Postman application, which will be responsible for getting access by making an API call to get tokens from the Authorization Server.

For testing authorization from Postman need to set up these under “App registration”:

  1. Navigate to the newly created App registration and select “Certificates & secrets” to generate a new client secret for the App registration, make sure you save the “Value” of the newly created “Certificates & secrets” since it will be hidden
  2. One last step is to add what will be the call-back URL once Authentication is successful, for that we need to add an Authentication URL under the “Authentication” section. Click on the “Add a platform” button and since our client application is Postman, select “Web” > under “Redirect URIs” provide the Postman call back URL which is https://oauth.pstmn.io/v1/callback” and click “Configure” then click on “Save” to save the configuration
  3. That’s it, now follow the below steps in order to test the Authorization flow using Postman as a client application

Create a new folder under a collection in Postman for which will need to add auth details.

create a new folder inside a collection

Once the folder is created, add Auth details as per the details which are present under “endpoints” in the “overview” section of “App registration”.

Under “Endpoint” where you will get all token URLs associated with App registration

Copy “OAuth 2.0 authorization endpoint (v2)” & “OAuth 2.0 token endpoint (v2)” which were present under “endpoints” and add the exact auth details under a newly created folder in Postman.

Note: To make Postman a client application, add https://oauth.pstmn.io/v1/callback URL under “Authentication” as a Web URL.

Adding of postman URL as a client in App registration

Then in postman under “Configure New Token” add the below details

  1. Grant Type: Authorization code (with PKCE)
  2. Auth URL: “OAuth 2.0 authorization endpoint (v2)”
  3. Access Token URL: “OAuth 2.0 token endpoint (v2)”
  4. Client ID: copy “Application (client) ID” under “overview” in “App registration”
  5. Client Secret: The “Value” which is present under “client secrets” in the “Certificates & secrets” section
  6. Scope: add the scope which is created earlier under “App registration”
After adding all the above details to the postman

Once all these details are created, click on the save and click on the “Get New Access Token” button this will open a new window in the browser and once user credentials are validated then it will navigate back to Postman, where you will get a new token. Click on “Proceed” to Get Access Token.

On successful authentication from the Postman

Conclusion

That’s it, these are the steps which need to be performed in order to secure a Spring Boot Application using the Azure active directory.

About the Author:
Pradeep Maiya is a Junior Java Developer here at Version 1.

--

--