page_type | languages | products | name | urlFragment | description | ||||
---|---|---|---|---|---|---|---|---|---|
sample |
|
|
Java Servlet Web App utilizing MSAL4J to authenticate users into Azure Active Directory B2C (Azure AD B2C) |
ms-identity-b2c-java-servlet-webapp-authentication |
This sample demonstrates a Java Servlet webapp that signs in users with Azure AD B2C |
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- Deployment
- More information
- Community Help and Support
- Contributing
- Code of Conduct
This sample demonstrates a Java Servlet web application that authenticates users against Azure Active Directory B2C (Azure AD B2C) using the the Microsoft Authentication Library for Java (MSAL4J).
- The client Java Servlet web application uses MSAL4J to sign-in users and obtains an ID Token from Azure AD B2C:
- The ID Token proves that the user has successfully authenticated against a Azure AD B2C tenant.
File/folder | Description |
---|---|
AuthHelper.java |
Helper functions for authentication. |
Config.java |
Runs on startup and configures properties reader and logger. |
authentication.properties |
Azure AD 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. |
- JDK Version 14 or higher
- Maven 3
- Tomcat 9
- An Azure AD B2C tenant. For more information see: How to get an Azure AD B2C tenant
- A user account in your Azure AD B2C.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-b2c-java-servlet-webapp-authentication.git
or download and extract the repository .zip file.
⚠️ To avoid file path length limitations on Windows, clone the repository into a directory near the root of your hard drive.
cd project-directory
mvn install -f pom.xml
Expand this section to see manual steps for configuring your own tenant:
As a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD B2C 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 Azure AD B2C tenant.
Please refer to Tutorial: Create user flows in Azure Active Directory B2C to create common user flows like sign up, sign in, edit profile, and passowrd reset.
You may consider creating Custom policies in Azure Active Directory B2C as well, however, this is beyond the scope of this tutorial.
Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C
-
Navigate to the Azure portal and select the Azure AD B2C 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
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 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, click on the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
-
In the Client secrets section, click on 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 concerns.
- The generated key value will be displayed when you click 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 Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
Configure the WebApp app (ms-identity-b2c-java-servlet-webapp-authentication) to use your app registration
Open the project in your IDE (like Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the authentication.properties file.
- Find the key
aad.clientId
and replace the existing value with the application ID (clientId) of thems-identity-b2c-java-servlet-webapp-authentication
application from the Azure portal. - Find the app key
aad.secret
and replace the existing value with the key you saved during the creation of thems-identity-b2c-java-servlet-webapp-authentication
application from the Azure portal. - Find the app key
aad.scopes
and replace the existing application clientId with the value you placed intoaad.clientId
in step 1 of this section. - Find the app key
aad.authority
and replace the first instance offabrikamb2c
with the name of the AAD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal. - Find the app key
aad.authority
and replace the second instance offabrikamb2c
with the name of the AAD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal. - Find the app key
aad.signInPolicy
and replace it with the name of the sign-up/sign-in userflow policy you created in the AAD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal. - Find the app key
aad.passwordResetPolicy
and replace it with the name of the password reset userflow policy you created in the AAD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal. - Find the app key
aad.editProfilePolicy
and replace it with the name of the edit profile userflow policy you created in the AAD B2C tenant in which you created thems-identity-b2c-java-servlet-webapp-authentication
application in the Azure portal.
-
Make certain that your Tomcat server is running and you have privileges to deploy a webapp to it.
-
Make certain that it serves the web app on
http://localhost:8080
(or change the base addresses listed in the authentication.properties file and in the AAD app registration). -
Compile and package the project using Maven:
cd project-directory mvn package -f pom.xml
-
Find the resulting
.war
file in./target/ms-identity-b2c-java-servlet-webapp-authentication.war
and upload it to your server. -
Ensure that the context path that the app is served on is
http://localhost:8080/ms-identity-b2c-java-servlet-webapp-authentication
(or change the addresses listed in the authentication.properties file and in the AAD app registration). -
Open your browser and navigate to
http://localhost:8080/ms-identity-b2c-java-servlet-webapp-authentication/index
- 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). - Follow the instructions on the next page to sign in with an account of your chosen identity provider.
- Note the context-sensitive button now says
Sign out
and displays your username to its left. - The middle of the screen now has an option to click for ID Token Details: click it to see some of the ID token's decoded claims.
- You also have the option of editing your profile. Click the link to edit details like your display name, place of residence, and profession.
- You can also use the button on the top right to sign out.
- After signing out, click this link to the token details page to observe how the app displays a
401: unauthorized
error instead of the ID token claims.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
This sample shows how to use MSAL4J to sign in users into your Azure AD B2C tenant.
A ConfidentialClientApplication instance is created in the AuthHelper.java class. This object helps craft the AAD 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 need to be provided upon 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 or profile-edit or password-reset.
In this sample, these values are read from the authentication.properties file using a properties reader in the class Config.java.
-
The first step of the sign-in process is to send a request to the
/authorize
endpoint on for our Azure Active Directory B2C Tenant. Our MSAL4J ConfidentialClientApplication instance is leveraged to construct an authorization request URL, and our app redirects the browser to this URL.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);
- AuthorizationRequestUrlParameters: Parameters that must be set in order to build an AuthorizationRequestUrl.
- REDIRECT_URI: Where AAD B2C will redirect the browser (along with auth code) after collecting 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 AAD B2C to also contain an Access Token.
- In order for AAD B2C to dispense an access token as well as an ID Token, the request must include an additional resource scope.
- Since 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.
- Full list of scopes requested by the app can be found in the authentication.properties file.
- Normally, the three scopes
- ResponseMode.QUERY: AAD 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: AAD 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 AAD redirect callback. The state variable ensures that AAD requests to the /auth_redirect endpoint are actually from AAD authorization requests originating from this app and this session, thereby preventing CSRF attacks.
- 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 AAD, thereby ensuring that there is 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 our app's redirect endpoint. A valid request to this endpoint will contain an authorization code.
-
Our ConfidentialClientApplication instance then exchanges this authorization code for an ID Token and Access Token from Azure Active Directory B2C.
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();
- 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.
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 class MsalAuthSession.java:
msalAuth.setAuthenticated(true); msalAuth.setUsername(msalAuth.getIdTokenClaims().get("name"));
- 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 Azure AD.
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 [azure-active-directory
azure-ad-b2c
ms-identity
adal
msal
].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following 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.
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.