Skip to content

Latest commit

 

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

page_type sample
languages
java
products
azure
msal-java
microsoft-entra-id
entra
urlFragment msal-java-spring-boot-sign-in
description This sample demonstrates a Java Spring MVC web app that authenticates users with Microsoft Entra ID

Enable your Java Spring Boot web app to sign in users on your Microsoft Entra tenant with the Microsoft identity platform

Overview

This sample demonstrates a Java Spring MVC web app that signs in users on your Microsoft Entra tenant using the Microsoft Entra ID Spring Boot Starter client library for Java. It uses the OpenID Connect protocol.

Overview

Scenario

  1. The client Java Spring MVC web app leverages the Microsoft Entra ID Spring Boot Starter client library for Java to sign-in a user and obtain an ID Token from Microsoft Entra ID.
  2. The ID Token proves that the user has successfully authenticated with Microsoft Entra ID and allows the user to access protected routes.

Overview

Contents

File/folder Description
AppCreationScripts/ Scripts to automatically configure Microsoft Entra app registrations.
pom.xml Application dependencies.
src/main/resources/templates/ Thymeleaf Templates for UI.
src/main/resources/application.yml Application and Microsoft Entra ID Boot Starter Library Configuration.
src/main/java/com/microsoft/azuresamples/msal4j/msidentityspringbootwebapp/ This directory contains the main application entry point, controller, and config classes.
.../MsIdentitySpringBootWebappApplication.java Main class.
.../SampleController.java Controller with endpoint mappings.
.../SecurityConfig.java Security Configuration (e.g., which routes require authentication?).
.../Utilities.java Utility Class (e.g., filter ID token claims
CHANGELOG.md List of changes to the sample.
CONTRIBUTING.md Guidelines for contributing to the sample.
LICENSE The license for the sample.

Prerequisites

Setup

Clone or download this repository

From your shell or command line:

    git clone https://github.com/Azure-Samples/ms-identity-msal-java-samples
    cd ms-identity-msal-java-samples
    cd .\4-spring-web-app\1-Authentication\sign-in\

or download and extract the repository .zip file.

⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.

Register the sample application(s) with your Microsoft Entra tenant

There is one project in this sample. To register it, you can:

  • follow the steps below for manually register your apps
  • or use PowerShell scripts that:
    • automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you.
    • modify the projects' configuration files.
Expand this section if you want to use this automation:

⚠️ If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.

  1. On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory

  2. If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.

  3. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  4. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.

  5. In PowerShell run:

    cd .\AppCreationScripts\
    .\Configure.ps1

    Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

Choose the Microsoft Entra tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Microsoft Entra admin center.
  2. If your account is present in more than one Microsoft Entra tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Microsoft Entra tenant.

Register the webApp app (java-spring-webapp-auth)

  1. Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. In the Register an application page that appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example java-spring-webapp-auth.
    • Under Supported account types, select Accounts in this organizational directory only.
    • In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI: http://localhost:8080/login/oauth2/code/.
  4. Select Register to create the application.
  5. In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  6. Select Save to save your changes.
  7. In the app's registration screen, select the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
  8. In the Client secrets section, select New client secret:
    • Type a key description (for instance app secret),
    • Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security posture.
    • The generated key value will be displayed when you select the Add button. Copy the generated value for use in the steps later.
    • You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Microsoft Entra admin center before navigating to any other screen or blade.

Configure the webApp app (java-spring-webapp-auth) to use your app registration

Open the project in your IDE (Visual Studio Code or IntelliJ IDEA) to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the src\main\resources\application.yml file.
  2. Find the key Enter_Your_Tenant_ID_Here and replace the existing value with your Microsoft Entra tenant ID.
  3. Find the key Enter_Your_Client_ID_Here and replace the existing value with the application ID (clientId) of java-spring-webapp-auth app copied from the Microsoft Entra admin center.
  4. Find the key Enter_Your_Client_Secret_Here and replace the existing value with the key you saved during the creation of java-spring-webapp-auth copied from the Microsoft Entra admin center.

Running the sample

  1. Open a terminal or the integrated VSCode terminal.
  2. In the same directory as this readme file, run mvn clean compile spring-boot:run.
  3. Open your browser and navigate to http://localhost:8080.

Experience

Explore the sample

  • Note the signed-in or signed-out status displayed at the center of the screen.
  • Click the context-sensitive button at the top right (it will read Sign In on first run)
    • Alternatively, click the link to token details. Since this is a protected page that requires authentication, you'll be automatically redirected to the sign-in page.
  • Follow the instructions on the next page to sign in with an account in the Microsoft Entra tenant.
  • On the consent screen, note the scopes that are being requested.
  • Upon successful completion of the sign-in flow, you should be redirected to the home page (sign in status) or token details page, depending on which button triggered your sign-in flow.
  • Note the context-sensitive button now says Sign out and displays your username to its left.
  • If you are on the home page, you'll see an option to click ID Token Details: click it to see some of the ID token's decoded claims.
  • You can also use the button on the top right to sign out. The status page will reflect this.

ℹ️ Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

About the code

This sample demonstrates how to use Microsoft Entra ID Spring Boot Starter client library for Java to sign in users into your Microsoft Entra tenant. It also makes use of Spring Oauth2 Client and Spring Web boot starters. It uses claims from ID Token obtained from Microsoft Entra ID to display details of the signed-in user.

Project Initialization

Create a new Java Maven project and copy the pom.xml file from this project, and the src folder of this repository.

If you'd like to create a project like this from scratch, you may use Spring Initializer:

  • For Packaging, select Jar
  • For Java select version 17
  • For Dependencies, add the following:
    • Microsoft Entra ID
    • Spring Oauth2 Client
    • Spring Web
  • Be sure that it comes with Azure SDK version 3.3 or higher. If not, please consider replacing the pre-configured pom.xml with the pom.xml from this repository.

ID Token Claims

To extract token details, make use of Spring Security's AuthenticationPrincipal and OidcUser object in a request mapping. See the Sample Controller for an example of this app making use of ID Token claims.

import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
//...
@GetMapping(path = "/some_path")
public String tokenDetails(@AuthenticationPrincipal OidcUser principal) {
    Map<String, Object> claims = principal.getIdToken().getClaims();
}

Sign-in and sign-out links

To sign in, you must make a request to the Microsoft Entra ID sign-in endpoint that is automatically configured by Microsoft Entra ID Spring Boot Starter client library for Java.

<a class="btn btn-success" href="/oauth2/authorization/azure">Sign In</a>

To sign out, you must make POST request to the logout endpoint.

<form action="#" th:action="@{/logout}" method="post">
  <input class="btn btn-warning" type="submit" value="Sign Out" />
</form>

Authentication-dependent UI elements

This app has some simple logic in the UI template pages for determining content to display based on whether the user is authenticated or not. For example, the following Spring Security Thymeleaf tags may be used:

<div sec:authorize="isAuthenticated()">
  this content only shows to authenticated users
</div>
<div sec:authorize="isAnonymous()">
  this content only shows to not-authenticated users
</div>

Protecting routes with aadwebsecurityconfigureradapter

By default, this app protects the ID Token Details page so that only logged-in users can access it. This app uses configures these routes from the app.protect.authenticated property from the application.yml file. To configure your app's specific requirements, provide a self-defined configuration. For an example, see this app's SecurityConfig class.

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig  {
    
    @Value("${app.protect.authenticated}")
    private String[] allowedOrigins;
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // @formatter:off
        http.apply(AadWebApplicationHttpSecurityConfigurer.aadWebApplication())
        .and()
        .authorizeHttpRequests()
        .anyRequest().authenticated();
        // @formatter:on
        return http.build();
    }    
}

Deployment

Deploy to Azure App Service. Prepare your app for deployment to Azure App Service, configure authentication parameters and use various Azure services for managing your operations.

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [microsoft-entra-id azure-ad-b2c ms-identity adal msal, java].

If you find a bug in the sample, raise the issue on GitHub Issues.

To provide feedback on or suggest features for Microsoft Entra ID, visit User Voice page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages