Enable sign-in for Java JBoss EAP apps using MSAL4J with Azure Active Directory B2C
This article demonstrates a Java JBoss EAP application that authenticates users against Azure Active Directory B2C (Azure AD B2C) using the Microsoft Authentication Library for Java (MSAL4J).
The following diagram shows the topology of the app:
The app uses MSAL4J to sign in users and obtain an ID token from Azure AD B2C. The ID token proves that the user is authenticated against a Azure AD B2C tenant.
Prerequisites
- JDK version 8 or higher
- Maven 3
- An Azure AD B2C tenant. For more information, see Tutorial: Create an Azure Active Directory B2C tenant
- A user account in your Azure AD B2C tenant.
Recommendations
- Some familiarity with the Java / Jakarta Servlets.
- Some familiarity with Linux/OSX terminal or Windows PowerShell.
- jwt.ms for inspecting your tokens.
- Fiddler for monitoring your network activity and troubleshooting.
- Follow the Microsoft Entra ID Blog to stay up-to-date with the latest developments.
Set up the sample
The following sections show you how to set up the sample application.
Clone or download the sample repository
To clone the sample, open a Bash window and use the following command:
git clone https://github.com/Azure-Samples/ms-identity-msal-java-samples.git
cd 3-java-servlet-web-app/1-Authentication/sign-in-b2c
Alternatively, navigate to the ms-identity-msal-java-samples repository, then download it as a .zip file and extract it to your hard drive.
Important
To avoid file path length limitations on Windows, clone or extract the repository into a directory near the root of your hard drive.
Register the sample application with your Azure AD B2C tenant
The sample comes with a preregistered application for testing purposes. If you would like to use your own Azure AD B2C tenant and application, follow the steps in the following sections to register and configure the application in the Azure portal. Otherwise, continue with the steps for Run the sample.
Choose the Azure AD B2C tenant where you want to create your applications
To choose your tenant, use the following steps:
Sign in to the Azure portal.
If your account is present in more than one Azure AD B2C tenant, select your profile in the corner of the Azure portal, and then select Switch directory to change your session to the desired Azure AD B2C tenant.
Create user flows and custom policies
To create common user flows like sign-up, sign-in, profile edit, and password reset, see Tutorial: Create user flows in Azure Active Directory B2C.
You should consider creating Custom policies in Azure Active Directory B2C as well, however, this is beyond the scope of this tutorial.
Add external identity providers
See Tutorial: Add identity providers to your applications in Azure Active Directory B2C.
Register the app (ms-identity-b2c-java-servlet-webapp-authentication)
To register the app, use the following steps:
Navigate to the Azure portal and select Azure AD B2C.
Select App Registrations on the navigation pane, then select New registration.
In the Register an application page that appears, enter the following application registration information:
- In the Name section, enter a meaningful application name for display to users of the app - for example,
ms-identity-b2c-java-servlet-webapp-authentication
. - Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI:
http://localhost:8080/ms-identity-b2c-java-servlet-webapp-authentication/auth_redirect
.
- In the Name section, enter a meaningful application name for display to users of the app - for example,
Select Register to create the application.
On the app's registration page, find and copy the Application (client) ID value to use later. You use this value in your app's configuration file or files.
Select Save to save your changes.
On the app's registration page, select Certificates & secrets on the navigation pane to open the page where you can generate secrets and upload certificates.
In the Client secrets section, select New client secret.
Type a description - for example, app secret.
Select one of the available durations: In 1 year, In 2 years, or Never Expires.
Select Add. The generated value is displayed.
Copy and save the generated value for use in later steps. You need this value for your code's configuration files. This value isn't displayed again, and you can't retrieve it by any other means. So, be sure to save it from the Azure portal before you navigate to any other screen or pane.
Configure the app (ms-identity-b2c-java-servlet-webapp-authentication) to use your app registration
Use the following steps to configure the app:
Note
In the following steps, ClientID
is the same as Application ID
or AppId
.
Open the project in your IDE.
Open the ./src/main/resources/authentication.properties file.
Find the
aad.clientId
property and replace the existing value with the application ID orclientId
of thems-identity-b2c-java-servlet-webapp-authentication
application from the Azure portal.Find the
aad.secret
property and replace the existing value with the value you saved during the creation of thems-identity-b2c-java-servlet-webapp-authentication
application from the Azure portal.Find the
aad.scopes
property and replace the existing application clientId with the value you placed intoaad.clientId
in step 1 of this section.Find the
aad.authority
property and replace the first instance offabrikamb2c
with the name of the Azure AD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.Find the
aad.authority
property and replace the second instance offabrikamb2c
with the name of the Azure AD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.Find the
aad.signInPolicy
property and replace it with the name of the sign-up/sign-in user-flow policy you created in the Azure AD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.Find the
aad.passwordResetPolicy
property and replace it with the name of the password reset user-flow policy you created in the Azure AD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.Find the
aad.editProfilePolicy
property and replace it with the name of the edit profile user-flow policy you created in the Azure AD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.
Build the sample
To build the sample using Maven, navigate to the directory containing the pom.xml file for the sample, and then run the following command:
mvn clean package
This command generates a .war file that you can run on various application servers.
Run the sample
The following sections show you how to deploy the sample to Azure App Service.
Prerequisites
Maven Plugin for Azure App Service apps
If Maven isn't your preferred development tool, see the following similar tutorials that use other tools:
Configure the Maven plugin
The deployment process to Azure App Service uses your Azure credentials from the Azure CLI automatically. If the Azure CLI isn't installed locally, then the Maven plugin authenticates with OAuth or device sign-in. For more information, see authentication with Maven plugins.
Use the following steps to configure the plugin:
Run the Maven command shown next to configure the deployment. This command helps you to set up the App Service operating system, Java version, and Tomcat version.
mvn com.microsoft.azure:azure-webapp-maven-plugin:2.12.0:config
For Create new run configuration, press Y, then press Enter.
For Define value for OS, press 2 for Linux, then press Enter.
For Define value for javaVersion, press 2 for Java 11, then press Enter.
For Define value for webContainer, press 1 for JBosseap7, then press Enter.
For Define value for pricingTier, press Enter to select the default P1v3 tier.
For Confirm, press Y, then press Enter.
The following example shows the output of the deployment process:
Please confirm webapp properties
AppName : msal4j-servlet-auth-1707220080695
ResourceGroup : msal4j-servlet-auth-1707220080695-rg
Region : centralus
PricingTier : P1v3
OS : Linux
Java Version: Java 11
Web server stack: JBosseap 7
Deploy to slot : false
Confirm (Y/N) [Y]:
[INFO] Saving configuration to pom.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 26.196 s
[INFO] Finished at: 2024-02-06T11:48:16Z
[INFO] ------------------------------------------------------------------------
After you've confirmed your choices, the plugin adds the plugin configuration and required settings to your project's pom.xml file to configure your app to run in Azure App Service.
The relevant portion of the pom.xml file should look similar to the following example:
<build>
<plugins>
<plugin>
<groupId>com.microsoft.azure</groupId>
<artifactId>>azure-webapp-maven-plugin</artifactId>
<version>x.xx.x</version>
<configuration>
<schemaVersion>v2</schemaVersion>
<resourceGroup>your-resourcegroup-name</resourceGroup>
<appName>your-app-name</appName>
...
</configuration>
</plugin>
</plugins>
</build>
You can modify the configurations for App Service directly in your pom.xml. Some common configurations are listed in the following table:
Property | Required | Description | Version |
---|---|---|---|
schemaVersion |
false | The version of the configuration schema. Supported values are v1 and v2 . |
1.5.2 |
subscriptionId |
false | The subscription ID. | 0.1.0+ |
resourceGroup |
true | The Azure resource group for your app. | 0.1.0+ |
appName |
true | The name of your app. | 0.1.0+ |
region |
false | The region in which to host your app. The default value is centralus . For valid regions, see Supported Regions. |
0.1.0+ |
pricingTier |
false | The pricing tier for your app. The default value is P1v2 for a production workload. The recommended minimum value for Java development and testing is B2 . For more information, see App Service Pricing |
0.1.0+ |
runtime |
false | The runtime environment configuration. For more information, see Configuration Details. | 0.1.0+ |
deployment |
false | The deployment configuration. For more information, see Configuration Details. | 0.1.0+ |
For the complete list of configurations, see the plugin reference documentation. All the Azure Maven plugins share a common set of configurations. For these configurations, see Common Configurations. For configurations specific to Azure App Service, see Azure app: Configuration Details.
Be sure to save aside the appName
and resourceGroup
values for later use.
Prepare the app for deployment
When you deploy your application to App Service, your redirect URL changes to the redirect URL of your deployed app instance. Use the following steps to change these settings in your properties file:
Navigate to your app's authentication.properties file and change the value of
app.homePage
to your deployed app's domain name, as shown in the following example. For example, if you choseexample-domain
for your app name in the previous step, you must now usehttps://example-domain.azurewebsites.net
for theapp.homePage
value. Be sure that you've also changed the protocol fromhttp
tohttps
.# app.homePage is by default set to dev server address and app context path on the server # for apps deployed to azure, use https://your-sub-domain.azurewebsites.net app.homePage=https://<your-app-name>.azurewebsites.net
After saving this file, use the following command to rebuild your app:
mvn clean package
Important
In this same authentication.properties file you have a setting for your aad.secret
. It isn't a good practice to deploy this value to App Service. Neither is it a good practice to leave this value in your code and potentially push it up to your git repository. For removing this secret value from your code, you can find more detailed guidance in the Deploy to App Service - Remove secret section. This guidance adds extra steps for pushing the secret value to Key Vault and to use Key Vault References.
Update your Microsoft Entra ID app registration
Because the redirect URI changes to your deployed app to Azure App Service, you also need to change the redirect URI in your Microsoft Entra ID app registration. Use the following steps to make this change:
Navigate to the Microsoft identity platform for developers App registrations page.
Use the search box to search for your app registration - for example,
java-servlet-webapp-authentication
.Open your app registration by selecting its name.
Select Authentication from the menu.
In the Web - Redirect URIs section, select Add URI.
Fill out the URI of your app, appending
/auth/redirect
- for example,https://<your-app-name>.azurewebsites.net/auth/redirect
.Select Save.
Deploy the app
You're now ready to deploy your app to Azure App Service. Use the following command to make sure you're signed in to your Azure environment to execute the deployment:
az login
With all the configuration ready in your pom.xml file, you can now use the following command to deploy your Java app to Azure:
mvn package azure-webapp:deploy
After deployment is completed, your application is ready at http://<your-app-name>.azurewebsites.net/
. Open the URL with your local web browser, where you should see the start page of the msal4j-servlet-auth
application.
Explore the sample
Use the following steps to explore the sample:
- Notice the signed-in or signed-out status displayed at the center of the screen.
- Select the context-sensitive button in the corner. This button reads Sign In when you first run the app.
- On the next page, follow the instructions and sign in with an account of your chosen identity provider.
- Notice that the context-sensitive button now says Sign out and displays your username.
- Select ID Token Details to see some of the ID token's decoded claims.
- You also have the option of editing your profile. Select the link to edit details like your display name, place of residence, and profession.
- Use the button in the corner to sign out.
- After signing out, navigate to the following URL for the token details page:
http://localhost:8080/ms-identity-b2c-java-servlet-webapp-authentication/auth_token_details
. Here, you can observe how the app displays a401: unauthorized
error instead of the ID token claims.
About the code
This sample demonstrates how to use MSAL4J to sign in users into your Azure AD B2C tenant.
Contents
The following table shows the contents of the sample project folder:
File/folder | Description |
---|---|
AuthHelper.java | Helper functions for authentication. |
Config.java | Runs on startup and configures properties reader and logger. |
authentication.properties | Microsoft Entra ID and program configuration. |
AuthenticationFilter.java | Redirects unauthenticated requests to protected resources to a 401 page. |
MsalAuthSession | Instantiated with an HttpSession . Stores all MSAL related session attributes in session attribute. |
____Servlet.java | All of the endpoints available are defined in .java classes ending in ____Servlet.java. |
CHANGELOG.md | List of changes to the sample. |
CONTRIBUTING.md | Guidelines for contributing to the sample. |
LICENSE | The license for the sample. |
ConfidentialClientApplication
A ConfidentialClientApplication
instance is created in the AuthHelper.java file, as shown in the following example. This object helps craft the Azure AD B2C authorization URL and also helps exchange the authentication token for an access token.
IClientSecret secret = ClientCredentialFactory.createFromSecret(SECRET);
confClientInstance = ConfidentialClientApplication
.builder(CLIENT_ID, secret)
.b2cAuthority(AUTHORITY + policy)
.build();
The following parameters are used for instantiation:
- The Client ID of the app.
- The client secret, which is a requirement for Confidential Client Applications.
- The Azure AD B2C Authority concatenated with the appropriate
UserFlowPolicy
for sign-up, sign-in, profile-edit, or password-reset.
In this sample, these values are read from the authentication.properties file using a properties reader in the Config.java file.
Step-by-step walkthrough
The following steps provide a walkthrough of the app's functionality:
The first step of the sign-in process is to send a request to the
/authorize
endpoint for your Azure Active Directory B2C tenant. The MSAL4JConfidentialClientApplication
instance is used to construct an authorization request URL, and the app redirects the browser to this URL, as shown in the following example:final ConfidentialClientApplication client = getConfidentialClientInstance(policy); final AuthorizationRequestUrlParameters parameters = AuthorizationRequestUrlParameters .builder(REDIRECT_URI, Collections.singleton(SCOPES)).responseMode(ResponseMode.QUERY) .prompt(Prompt.SELECT_ACCOUNT).state(state).nonce(nonce).build(); final String redirectUrl = client.getAuthorizationRequestUrl(parameters).toString(); Config.logger.log(Level.INFO, "Redirecting user to {0}", redirectUrl); resp.setStatus(302); resp.sendRedirect(redirectUrl);
The following list describes the features of this code:
AuthorizationRequestUrlParameters
: Parameters that must be set in order to build an AuthorizationRequestUrl.REDIRECT_URI
: Where Azure AD B2C redirects the browser - along with the auth code - after collecting the user credentials.SCOPES
: Scopes are permissions requested by the application.Normally, the three scopes
openid profile offline_access
would suffice for receiving an ID token response. However, MSAL4J requires all responses from Azure AD B2C to also contain an access token.In order for Azure AD B2C to dispense an access token as well as an ID token, the request must include an additional resource scope. Because this app doesn't actually require an external resource scope, it adds its own client ID as a fourth scope in order to receive an access token.
You can find a full list of scopes requested by the app in the authentication.properties file.
ResponseMode.QUERY
: Azure AD B2C can return the response as form params in an HTTP POST request or as query string params in an HTTP GET request.Prompt.SELECT_ACCOUNT
: Azure AD B2C should ask the user to select the account that they intend to authenticate against.state
: A unique variable set by the app into the session on each token request and destroyed after receiving the corresponding Azure AD B2C redirect callback. The state variable ensures that Azure AD B2C requests to the/auth_redirect endpoint
are actually from Azure AD B2C authorization requests originating from this app and this session, thereby preventing CSRF attacks. This is done in the AADRedirectServlet.java file.nonce
: A unique variable set by the app into the session on each token request, and destroyed after receiving the corresponding token. This nonce is transcribed to the resulting tokens dispensed Azure AD B2C, thereby ensuring that there's no token-replay attack occurring.
The user is presented with a sign-in prompt by Azure Active Directory B2C. If the sign-in attempt is successful, the user's browser is redirected to the app's redirect endpoint. A valid request to this endpoint contains an authorization code.
The
ConfidentialClientApplication
instance then exchanges this authorization code for an ID token and access token from Azure Active Directory B2C, as shown in the following example:final AuthorizationCodeParameters authParams = AuthorizationCodeParameters .builder(authCode, new URI(REDIRECT_URI)) .scopes(Collections.singleton(SCOPES)).build(); final ConfidentialClientApplication client = AuthHelper .getConfidentialClientInstance(policy); final Future<IAuthenticationResult> future = client.acquireToken(authParams); final IAuthenticationResult result = future.get();
The following list describes the features of this code:
AuthorizationCodeParameters
: Parameters that must be set in order to exchange the Authorization Code for an ID and/or access token.authCode
: The authorization code that was received at the redirect endpoint.REDIRECT_URI
: The redirect URI used in the previous step must be passed again.SCOPES
: The scopes used in the previous step must be passed again.
If
acquireToken
is successful, the token claims are extracted and the nonce claim is validated against the nonce stored in the session, as shown in the following example:parseJWTClaimsSetAndStoreResultInSession(msalAuth, result, serializedTokenCache); validateNonce(msalAuth) processSuccessfulAuthentication(msalAuth);
If the nonce is successfully validated, authentication status is put into a server-side session, leveraging methods exposed by the
MsalAuthSession
class, as shown in the following example:msalAuth.setAuthenticated(true); msalAuth.setUsername(msalAuth.getIdTokenClaims().get("name"));
More information
- What is Azure Active Directory B2C?
- Application types that can be used in Active Directory B2C
- Recommendations and best practices for Azure Active Directory B2C
- Azure AD B2C session
- Microsoft Authentication Library (MSAL) for Java
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Microsoft Entra ID.
Phản hồi
https://aka.ms/ContentUserFeedback.
Sắp ra mắt: Trong năm 2024, chúng tôi sẽ dần gỡ bỏ Sự cố với GitHub dưới dạng cơ chế phản hồi cho nội dung và thay thế bằng hệ thống phản hồi mới. Để biết thêm thông tin, hãy xem:Gửi và xem ý kiến phản hồi dành cho