| page_type | sample | ||||
|---|---|---|---|---|---|
| languages |
|
||||
| products |
|
||||
| urlFragment | msal-java-authorization-groups | ||||
| description | This sample demonstrates how to create a Java Servlet web app that signs in users and restricts access to pages based on group membership with the Microsoft identity platform |
Enable your Java Servlet web app to sign in users and restrict access to pages using security groups and groups claims with the Microsoft identity platform
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Register the sample application with your Microsoft Entra tenant
- Running the sample
- Explore the sample
- Processing Groups claim in tokens, including handling overage
- We'd love your feedback!
- About the code
- Deploy to Azure
- More information
- Community Help and Support
- Contributing
This sample demonstrates how to create a Java Servlet web app that signs in users with Microsoft Authentication Library (MSAL) for Java and restricts access to pages based on Microsoft Entra ID security group membership.
An Identity Developer session covered Microsoft Entra app roles and security groups, featuring this scenario and how to handle the overage claim. Watch the video Using Security Groups and Application Roles in your apps
- This web application uses MSAL for Java (MSAL4J) to sign in users a Microsoft Entra tenant and obtains an ID Token from Microsoft Entra ID.
- The ID Token proves that a user has successfully authenticated with this tenant.
- The web application protects its routes according to user's authentication status and group membership.
| File/folder | Description |
|---|---|
AppCreationScripts/ |
Scripts to automatically configure Microsoft Entra app registrations. |
src/main/java/com/microsoft/azuresamples/msal4j/groupswebapp/ |
This directory contains the classes that define the web app's backend business logic. |
src/main/java/com/microsoft/azuresamples/msal4j/authservlets/ |
This directory contains the classes that are used for sign in and sign out endpoints. |
____Servlet.java |
All of the endpoints available are defined in .java classes ending in ____Servlet.java |
src/main/java/com/microsoft/azuresamples/msal4j/helpers/ |
Helper classes for authentication. |
AuthenticationFilter.java |
Redirects unauthenticated requests to protected endpoints to a 401 page. |
src/main/resources/authentication.properties |
Microsoft Entra ID and program configuration. |
src/main/webapp/ |
This directory contains the UI (JSP templates) |
CHANGELOG.md |
List of changes to the sample. |
CONTRIBUTING.md |
Guidelines for contributing to the sample. |
LICENSE |
The license for the sample. |
- JDK Version 8 or higher
- Maven 3
- a Microsoft Entra tenant. For more information on how to get a Microsoft Entra tenant, see How to get a Microsoft Entra tenant
- A user account in your own Microsoft Entra tenant.
- Two security groups, GroupAdmin and GroupMember, containing users you want to test with.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-java-servlet-webapp-authentication.git
cd 3-Authorization-II/groupsor 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.
There is one project in this sample. To register the app on the portal, you can:
- either follow manual configuration steps below
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
- by default, the automation scripts set up an application that works with accounts in your organizational directory only.
Expand this section if you want to use PowerShell automation.
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
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.
Register a new web app in the Microsoft Entra admin center. Following this guide, you must:
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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-servlet-webapp-groups. - Under Supported account types, select Accounts in this organizational directory only.
- In the Redirect URI section, select Web in the combo-box and enter the following redirect URI:
http://localhost:8080/msal4j-servlet-groups/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 Microsoft Entra admin center before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then:
- Ensure that the Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select User.Read and GroupMember.Read.All in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- GroupMember.Read.All requires admin consent. Select the Grant/revoke admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a Microsoft Entra tenant admin to do this.
Open the project in your IDE to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId". Remove the curly braces from the placeholder values as well.
- Open the
./src/main/resources/authentication.propertiesfile - Find the string
{enter-your-tenant-id-here}. Replace the existing value with:- Your Microsoft Entra tenant ID if you registered your app with the Accounts in this organizational directory only option.
- Find the string
{enter-your-client-id-here}and replace the existing value with the application ID (clientId) of thejava-servlet-webapp-groupsapplication copied from the Microsoft Entra admin center. - Find the string
{enter-your-client-secret-here}and replace the existing value with the key you saved during the creation of thejava-servlet-webapp-groupsapp, in the Microsoft Entra admin center.
You have two different options available to you on how you can further configure your application(s) to receive the groups claim.
- Receive all the groups that the signed-in user is assigned to in a Microsoft Entra tenant, including nested groups.
- Receive the groups claim values from a filtered set of groups that your application is programmed to work with (Not available in the Microsoft Entra ID Free edition).
To get the on-premise group's
samAccountNameorOn Premises Group Security Identifierinstead of Group ID, please refer to the document Configure group claims for applications with Microsoft Entra ID.
Configure your application to receive all the groups the signed-in user is assigned to, including nested groups
- In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
- Select the Add groups claim button on top to open the Edit Groups Claim screen.
- Select
Security groupsor theAll groups (includes distribution lists but not groups assigned to the application)option. Choosing both negates the effect ofSecurity Groupsoption. - Under the ID section, select
Group ID. This will result in Microsoft Entra ID sending the Object ID of the groups the user is assigned to in the groups claim of the ID Token that your app receives after signing-in a user.
Configure your application to receive the groups claim values from a filtered set of groups a user may be assigned to
- This option is useful when your application is interested in a selected set of groups that a signing-in user may be assigned to and not every security group this user is assigned to in the tenant. This option also saves your application from running into the overage issue.
- This feature is not available in the Microsoft Entra ID Free edition.
- Nested group assignments are not available when this option is utilized.
- In the app's registration screen, select the Token Configuration blade in the left to open the page where you can configure the claims provided tokens issued to your application.
- Select the Add groups claim button on top to open the Edit Groups Claim screen.
- Select
Groups assigned to the application.- Choosing additional options like
Security GroupsorAll groups (includes distribution lists but not groups assigned to the application)will negate the benefits your app derives from choosing to use this option.
- Choosing additional options like
- Under the ID section, select
Group ID. This will result in Microsoft Entra ID sending the Object ID of the groups the user is assigned to in thegroupsclaim of the ID Token. - If you are exposing a web API using the Expose an API option, then you can also choose the
Group IDoption under the Access section. This will result in Microsoft Entra ID sending the Object ID of the groups the user is assigned to in thegroupsclaim of the Access Token. - In the app's registration screen, select on the Overview blade in the left to open the Application overview screen. Select the hyperlink with the name of your application in Managed application in local directory (note this field title can be truncated for instance
Managed application in ...). When you select this link you will navigate to the Enterprise Application Overview page associated with the service principal for your application in the tenant where you created it. You can navigate back to the app registration page by using the back button of your browser. - Select the Users and groups blade in the left to open the page where you can assign users and groups to your application.
- Select the Add user button on the top row.
- Select User and Groups from the resultant screen.
- Choose the groups that you want to assign to this application.
- Click Select in the bottom to finish selecting the groups.
- Select Assign to finish the group assignment process.
- Your application will now receive these selected groups in the
groupsclaim when a user signing in to your app is a member of one or more these assigned groups.
- Select the Properties blade in the left to open the page that lists the basic properties of your application.Set the User assignment required? flag to Yes.
💡 Important security tip
When you set User assignment required? to Yes, Microsoft Entra ID will check that only users assigned to your application in the Users and groups blade are able to sign-in to your app. You can assign users directly or by assigning security groups they belong to.
⚠️ During Token Configuration, if you have chosen any other option except groupID (e.g. like DNSDomain\sAMAccountName) you should enter the group name (for examplecontoso.com\Test Group) instead of the object ID below:
- Open the
./src/main/resources/authentication.propertiesfile. - Find the string
{enter-your-admins-group-id-here}and replace the existing value with the object ID of the GroupAdmin group copied from the Microsoft Entra admin center. Remove the curly braces from the placeholder value as well. - Find the string
{enter-your-users-group-id-here}and replace the existing value with the object ID of the GroupMember group copied from the Microsoft Entra admin center. Remove the curly braces from the placeholder value as well.
- Navigate to the directory containing the pom.xml file for this sample (the same directory as this README), and run the following Maven command:
mvn clean package - This should generate a
.warfile which can be run on a variety of application servers
Our samples can be deployed to a number of application servers, such as Tomcat, WebLogic, or Webshpere, and MSAL Java itself can generally be integrated into existing applications without changes to your existing deployment set up.
You can find instructions for deploying our samples here on MSAL Java's Github wiki.
- 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) - 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.
- Note the context-sensitive button now says
Sign outand 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.
- Click the Groups button to see any information about security group membership for the signed in user.
- Click the Admin Only or Regular User buttons to access the groups claim protected endpoints.
- If your signed in user is in the GroupAdmin group, the user will be able to enter both pages.
- If your signed in user is in the GroupMember group, the user will be able to enter the Regular User page only.
- If your signed in user is in neither group, the user will be able to access to none of the two pages.
- You can also use the button on the top right to sign out.
- After signing out, click the link to
ID Token Detailsto observe that the app displays a401: unauthorizederror instead of the ID token claims when the user is not authorized.
ℹ️ 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.
The object id of the security groups the signed in user is member of is returned in the groups claim of the token.
{
...
"groups": [
"aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
"bbbbbbbb-1111-2222-3333-cccccccccccc",]
...
}To ensure that the token size doesn’t exceed HTTP header size limits, the Microsoft Identity Platform limits the number of object Ids that it includes in the groups claim.
If a user is member of more groups than the overage limit (150 for SAML tokens, 200 for JWT tokens, 6 for Single Page applications), then the Microsoft Identity Platform does not emit the group IDs in the groups claim in the token. Instead, it includes an overage claim in the token that indicates to the application to query the MS Graph API to retrieve the user’s group membership.
{
...
"_claim_names": {
"groups": "src1"
},
{
"_claim_sources": {
"src1": {
"endpoint":"[Graph Url to get this user's group membership from]"
}
}
...
}- You can use the
BulkCreateGroups.ps1provided in the App Creation Scripts folder to create a large number of groups and assign users to them. This will help test overage scenarios during development. Remember to change the user's objectId provided in theBulkCreateGroups.ps1script. - When you run this sample and an overage occurred, then you'd see the
_claim_namesin the home page after the user signs-in. - We strongly advise you use the group filtering feature (if possible) to avoid running into group overages.
- In case you cannot avoid running into group overage, we suggest you use the following logic to process groups claim in your token.
- Check for the claim
_claim_nameswith one of the values beinggroups. This indicates overage. - If found, make a call to the endpoint specified in
_claim_sourcesto fetch user’s groups. - If none found, look into the
groupsclaim for user’s groups.
- Check for the claim
When attending to overage scenarios, which requires a call to Microsoft Graph to read the signed-in user's group memberships, your app will need to have the GroupMember.Read.All for the getMemberObjects function to execute successfully.
Developers who wish to gain good familiarity of programming for Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
This sample uses MSAL for Java (MSAL4J) to sign a user in and obtain an ID token that may contain the groups claim. If there are too many groups for emission in the ID token, the sample leverages Microsoft Graph SDK for Java to obtain the group membership data from Microsoft Graph. Based on the groups the user belongs to, the signed in user will be able to access either none, one, or both of the protected pages, Admins Only and Regular Users.
If you want to replicate this sample's behavior, you must add these libraries (MSAL4J and MS Graph SDK) your projects using Maven. As a developer, you may choose to copy the pom.xml file, and the contents of the helpers and authservlets packages in the src/main/java/com/microsoft/azuresamples/msal4j package. You'll also need the authentication.properties file. These classes and files contain generic code that can be used in a wide array of applications. The rest of the sample may be copied as well, but the other classes and files are built specifically to address this sample's objective.
A ConfidentialClientApplication instance is created in the AuthHelper.java class. This object helps craft the Microsoft Entra authorization URL and also helps exchange the authentication token for an access token.
// getConfidentialClientInstance method
IClientSecret secret = ClientCredentialFactory.createFromSecret(SECRET);
confClientInstance = ConfidentialClientApplication
.builder(CLIENT_ID, secret)
.authority(AUTHORITY)
.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 Microsoft Entra authority, which includes your Microsoft Entra tenant ID.
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
/authorizeendpoint on for our Microsoft Entra tenant. Our MSAL4JConfidentialClientApplicationinstance is leveraged to construct an authorization request URL. Our app redirects the browser to this URL, which is where the user will sign in.final ConfidentialClientApplication client = getConfidentialClientInstance(); AuthorizationRequestUrlParameters parameters = AuthorizationRequestUrlParameters.builder(Config.REDIRECT_URI, Collections.singleton(Config.SCOPES)) .responseMode(ResponseMode.QUERY).prompt(Prompt.SELECT_ACCOUNT).state(state).nonce(nonce).build(); final String authorizeUrl = client.getAuthorizationRequestUrl(parameters).toString(); contextAdapter.redirectUser(authorizeUrl);
- AuthorizationRequestUrlParameters: Parameters that must be set in order to build an AuthorizationRequestUrl.
- REDIRECT_URI: Where Microsoft Entra ID will redirect the browser (along with auth code) after collecting user credentials. It must match the redirect URI in the Microsoft Entra app registration on Microsoft Entra admin center
- SCOPES: Scopes are permissions requested by the application.
- Normally, the three scopes
openid profile offline_accesssuffice for receiving an ID Token response. - Full list of scopes requested by the app can be found in the authentication.properties file. You can add more scopes like User.Read and so on.
- Normally, the three scopes
-
The user is presented with a sign-in prompt by Microsoft Entra ID. 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 Microsoft Entra ID.
// First, validate the state, then parse any error codes in response, then extract the authCode. Then: // build the auth code params: final AuthorizationCodeParameters authParams = AuthorizationCodeParameters .builder(authCode, new URI(Config.REDIRECT_URI)).scopes(Collections.singleton(Config.SCOPES)).build(); // Get a client instance and leverage it to acquire the token: final ConfidentialClientApplication client = AuthHelper.getConfidentialClientInstance(); final IAuthenticationResult result = client.acquireToken(authParams).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
acquireTokenis successful, the token claims are extracted. If the nonce check passes, the results are placed incontext(an instance ofIdentityContextData) and saved to the session. The application can then instantiate this from the session (by way of an instance ofIdentityContextAdapterServlet) whenever it needs access to it:// parse IdToken claims from the IAuthenticationResult: // (the next step - validateNonce - requires parsed claims) context.setIdTokenClaims(result.idToken()); // if nonce is invalid, stop immediately! this could be a token replay! // if validation fails, throws exception and cancels auth: validateNonce(context); // set user to authenticated: context.setAuthResult(result, client.tokenCache().serialize()); // handle groups overage if it has occurred. handleGroupsOverage(contextAdapter);
-
After previous step, group memberships may be extracted by calling
context.getGroups()(an instance ofIdentityContextData). -
If the user is a member of too many groups (>200), a call to
context.getGroups()might have been empty if it weren't for the call tohandleGroupsOverage(). Meanwhile,context.getGroupsOverage()will returntrue, signalling that an overage has occurred, and that getting the full list of groups will require a call to Microsoft Graph. SeehandleGroupsOverage()method inAuthHelper.javafor this application usescontext.setGroups()when there is an overage.
See AuthenticationFilter.java for how the sample app filters access to routes. In the authentication.properties file, the key app.protect.authenticated contains the comma-separated routes that are to be accessed by authenticated users only.
# e.g., /token_details requires any user to be signed in and does not require special groups claim
app.protect.authenticated=/token_detailsAny of the routes listed in the comma-separated rule sets under the app.protect.groups are also off-limits to non-authenticated authenticated users.
However, these routes also contain a space-separated list of group memberships: only users belonging to at least one of the corresponding groups will be able to access these routes after authenticating.
# define short names for group IDs here for the app. This will be useful in the next key (app.protect.groups).
# EXCLUDE the curly braces, they are in this file only as delimiters.
# example:
# app.groups=groupA abcdef-qrstuvw-xyz groupB abcdef-qrstuv-wxyz
app.groups=admin {enter-your-admins-group-id-here}, user {enter-your-users-group-id-here}
# A route and its corresponding group(s) that can view it, <space-separated>; the start of the next route & its group(s) is delimited by a <comma-and-space-separator>
# this says: /admins_only can be accessed by admin group, /regular_user can be accessed by admin group and user group
app.protect.groups=/admin_only admin, /regular_user admin user- Scopes tell Microsoft Entra ID the level of access that the application is requesting.
- Based on the requested scopes, Microsoft Entra ID presents a consent dialogue to the user upon signing in.
- If the user consents to one or more scopes and obtains a token, the scopes-consented-to are encoded into the resulting
access_token. - Note the scope requested by the application by referring to authentication.properties. By default, the application sets the scopes value to
GroupMember.Read.All. - This particular MS Graph API scope is required in case the application needs to call Graph for getting the user's group memberships.
Follow this guide to deploy this app to Azure App Service.
-
Microsoft identity platform (Microsoft Entra ID for developers)
-
Quickstart: Register an application with the Microsoft identity platform (Preview)
-
Understanding Microsoft Entra application consent experiences
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 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.
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com

