Configuring spring-boot-starter-oauth2-client to authenticate with Azure AD

3 min read 06-10-2024
Configuring spring-boot-starter-oauth2-client to authenticate with Azure AD


Authenticating Spring Boot Applications with Azure Active Directory using OAuth2

This article guides you through the process of integrating your Spring Boot application with Azure Active Directory (Azure AD) for secure authentication using the OAuth2 protocol. We'll leverage the spring-boot-starter-oauth2-client dependency to streamline this process.

The Challenge:

Modern applications often require secure user authentication. Azure AD offers a robust identity and access management solution, but integrating it with your Spring Boot application can seem daunting. This article will demystify the process, providing a step-by-step guide to achieve seamless authentication with Azure AD.

Scenario and Original Code:

Imagine a Spring Boot application that needs to access an API secured by Azure AD. Here's a basic example:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

This code represents a basic Spring Boot application without any authentication configuration. We will modify this application to enable Azure AD authentication.

Step-by-Step Configuration:

  1. Dependencies:

    • Add the following dependency to your pom.xml file:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-client</artifactId>
    </dependency>
    
  2. Azure AD Application Registration:

    • Create a new application registration in your Azure AD tenant.
    • Provide a name, redirect URI (e.g., http://localhost:8080/login/oauth2/code/azure) and select "Web" as the application type.
    • Note down the Application (client) ID and Directory (tenant) ID.
  3. Application Configuration:

    • Create an application.properties file in your Spring Boot project and configure the following:
    spring.security.oauth2.client.registration.azure.client-id=<YOUR_CLIENT_ID>
    spring.security.oauth2.client.registration.azure.client-secret=<YOUR_CLIENT_SECRET>
    spring.security.oauth2.client.registration.azure.client-name=azure
    spring.security.oauth2.client.registration.azure.scope=openid,profile,email
    spring.security.oauth2.client.registration.azure.authorization-grant-type=authorization_code
    spring.security.oauth2.client.registration.azure.redirect-uri=http://localhost:8080/login/oauth2/code/azure
    spring.security.oauth2.client.registration.azure.provider.issuer-uri=https://login.microsoftonline.com/<YOUR_TENANT_ID>/v2.0
    

    Explanation:

    • client-id: Your Azure AD application's client ID.
    • client-secret: Your Azure AD application's secret.
    • client-name: A name for your OAuth2 client registration.
    • scope: Defines the permissions you request from Azure AD (e.g., openid for user identity, profile for basic user information, email for user email).
    • authorization-grant-type: Specifies the OAuth2 grant type (in this case, authorization_code).
    • redirect-uri: The URI to redirect the user after successful authentication.
    • issuer-uri: The Azure AD endpoint for authentication.
  4. Security Configuration:

    • Add the following configuration to your SecurityConfig class:
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                    .oauth2Login()
                    .loginPage("/login")
                    .defaultSuccessUrl("/", true);
        }
    }
    

    Explanation:

    • authorizeRequests(): Configures the authorization rules for accessing specific routes. In this case, all requests require authentication.
    • oauth2Login(): Enables OAuth2 login with Azure AD.
    • loginPage("/login"): Specifies the login page.
    • defaultSuccessUrl("/", true): Sets the default URL to redirect to after successful authentication.

Additional Insights:

  • Token Management: Spring Security automatically manages access tokens and refreshes them as needed.
  • Authorization: You can use Spring Security's @PreAuthorize annotation or other mechanisms to restrict access to resources based on user roles and permissions granted by Azure AD.
  • Logging: Enable logging in your Spring Boot application to debug any authentication issues.

Conclusion:

By following these steps, you can successfully integrate your Spring Boot application with Azure AD using the OAuth2 protocol. This allows you to leverage the security and scalability of Azure AD while providing a smooth and secure user experience.

Resources: