| page_type | sample | ||||
|---|---|---|---|---|---|
| languages |
|
||||
| products |
|
||||
| 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
- Scenario
- Contents
- Prerequisites
- Setup
- Running the sample
- Explore the sample
- We'd love your feedback!
- About the code
- More information
- Community Help and Support
- Contributing
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.
- 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.
- The ID Token proves that the user has successfully authenticated with Microsoft Entra ID and allows the user to access protected routes.
| 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. |
- JDK Version 15. This sample has been developed on a system with Java 15 but may be compatible with other versions.
- Maven 3
- Java Extension Pack for Visual Studio Code is recommended for running this sample in VSCode.
- An Microsoft Entra ID tenant. For more information see: How to get a Microsoft Entra tenant
- A user account in your Microsoft Entra ID tenant. This sample will not work with a personal Microsoft account. Therefore, if you signed in to the Microsoft Entra admin center with a personal account and have never created a user account in your directory before, you need to do that now.
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.
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.
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
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.
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
-
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.
As a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- 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.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID service.
- Select the App Registrations blade on the left, then select New registration.
- 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/.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- 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.
- Select Save to save your changes.
- 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.
- 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.
- Type a key description (for instance
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".
- Open the
src\main\resources\application.ymlfile. - Find the key
Enter_Your_Tenant_ID_Hereand replace the existing value with your Microsoft Entra tenant ID. - Find the key
Enter_Your_Client_ID_Hereand replace the existing value with the application ID (clientId) ofjava-spring-webapp-authapp copied from the Microsoft Entra admin center. - Find the key
Enter_Your_Client_Secret_Hereand replace the existing value with the key you saved during the creation ofjava-spring-webapp-authcopied from the Microsoft Entra admin center.
- Open a terminal or the integrated VSCode terminal.
- In the same directory as this readme file, run
mvn clean compile spring-boot:run. - Open your browser and navigate to
http://localhost:8080.
- 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 Inon 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.
- Alternatively, click the link to
- 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) ortoken detailspage, depending on which button triggered your sign-in flow. - Note the context-sensitive button now says
Sign outand 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.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
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.
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.xmlwith thepom.xmlfrom this repository.
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();
}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>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>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();
}
}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.
- Microsoft identity platform (Microsoft Entra ID for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Quickstart: Register an application with the Microsoft identity platform (Preview)
- Quickstart: Configure a client application to access web APIs (Preview)
- Understanding Microsoft Entra application consent experiences
- Understand user and admin consent
- Application and service principal objects in Microsoft Entra ID
- National Clouds
- MSAL code samples
- Microsoft Entra ID Spring Boot Starter client library for Java
- Microsoft Authentication Library for Java (MSAL4J)
- MSAL4J Wiki
- ID Tokens
- Access Tokens
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.
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.
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.

