Secure Java WebLogic apps using roles and role claims
This article demonstrates a Java WebLogic app that uses OpenID Connect to sign in users and Microsoft Entra ID Application Roles (app roles) for authorization.
This application implements role-based access control (RBAC) using Microsoft Entra ID's application roles and role claims feature. Another approach is to use Microsoft Entra ID groups and group claims. Microsoft Entra ID groups and application roles aren't mutually exclusive. You can use them both to provide fine-grained access control.
You can also use RBAC with application roles and role claims to securely enforce authorization policies.
For a video that covers this scenario and this sample, see Implement authorization in your applications using app roles, security groups, scopes, and directory roles.
For more information about how the protocols work in this scenario and in other scenarios, see Authentication vs. authorization.
This application uses MSAL for Java (MSAL4J) to sign in a user and obtain an ID token from Microsoft Entra ID.
This sample first uses the MSAL for Java (MSAL4J) to sign in the user. On the home page it displays an option for the user to view the claims in their ID tokens. This application also enables the users to view a privileged admin page or a regular user page, depending on the app role they've been assigned to. The idea is to provide an example of how, within an application, access to certain functionality or pages is restricted to subsets of users depending on which role they belong to.
This kind of authorization is implemented using RBAC. With RBAC, an administrator grants permissions to roles, not to individual users or groups. The administrator can then assign roles to different users and groups to control who has access to certain content and functionality.
This sample application defines the following two Application Roles:
PrivilegedAdmin
: Authorized to access the Admins Only and the Regular Users pages.RegularUser
: Authorized to access the Regular Users page.
These application roles are defined in the Azure portal in the application's registration manifest. When a user signs into the application, Microsoft Entra ID emits a roles claim for each role granted individually to the user in the form of role membership.
You can assign users and groups to roles through the Azure portal.
Note
Role claims aren't present for guest users in a tenant if the https://login.microsoftonline.com/common/
endpoint is used as the authority to sign in users. You need to sign in a user to a tenanted endpoint like https://login.microsoftonline.com/tenantid
.
Prerequisites
- JDK version 8 or higher
- Maven 3
- A Microsoft Entra ID tenant. For more information, see How to get a Microsoft Entra ID tenant.
- A user account in your own Microsoft Entra ID tenant if you want to work with accounts in your organizational directory only - that is, single-tenant mode. If you haven't created a user account in your tenant yet, you should do so before proceeding. For more information, see How to create, invite, and delete users.
Recommendations
- Some familiarity with the Java / Jakarta Servlets.
- Some familiarity with Linux/OSX terminal.
- 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/3-Authorization-II/roles
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 Microsoft Entra ID tenant
There's one project in this sample. The following sections show you how to register the app using the Azure portal.
Choose the Microsoft Entra ID 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 Microsoft Entra ID tenant, select your profile in the corner of the Azure portal, and then select Switch directory to change your session to the desired Microsoft Entra ID tenant.
Register the app (java-servlet-webapp-roles)
First, register a new app in the Azure portal by following the instructions in Quickstart: Register an application with the Microsoft identity platform.
Then, use the following steps to complete the registration:
Navigate to the Microsoft identity platform for developers App registrations page.
Select New registration.
In the Register an application page that appears, enter the following app registration information:
In the Name section, enter a meaningful application name for display to users of the app - for example,
java-servlet-webapp-roles
.Under Supported account types, select one of the following options:
- Select Accounts in this organizational directory only if you're building an application for use only by users in your tenant - that is, a single-tenant application.
In the Redirect URI section, select Web in the combo-box and enter the following redirect URI:
http://localhost:8080/msal4j-servlet-roles/auth/redirect
.
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.
Define the application roles
To define the app roles, use the following steps:
Still on the same app registration, select App roles on the navigation pane.
Select Create app role, then enter the following values:
- For Display name, enter a suitable name - for example, PrivilegedAdmin.
- For Allowed member types, choose User.
- For Value, enter PrivilegedAdmin.
- For Description, enter PrivilegedAdmins who can view the Admin Page.
Select Create app role, then enter the following values:
- For Display name, enter a suitable name - for example, RegularUser.
- For Allowed member types, choose User.
- For Value, enter RegularUser.
- For Description, enter RegularUsers who can view the User Page.
Select Apply to save your changes.
Assign users to the application roles
To add users to the app role defined earlier, follow the guidelines here: Assign users and groups to roles.
Configure the app (java-servlet-webapp-roles) 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 authentication.properties file.
Find the string
{enter-your-tenant-id-here}
. Replace the existing value with your Microsoft Entra ID tenant ID.Find the string
{enter-your-client-id-here}
and replace the existing value with the application ID orclientId
of thejava-servlet-webapp-call-graph
application copied from the Azure portal.Find the string
{enter-your-client-secret-here}
and replace the existing value with the value you saved during the creation of thejava-servlet-webapp-roles
app, in the Azure portal.Find the
app.roles
property and make sure the value is set toapp.roles=admin PrivilegedAdmin, user RegularUser
, or substitute the names of your specific roles.
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.
Deploy the sample
These instructions assume that you installed WebLogic and set up some server domain.
Before you can deploy to WebLogic, use the following steps to make some configuration changes in the sample itself and then build or rebuild the package:
In the sample, find the application.properties or authentication.properties file where you configured the client ID, tenant, redirect URL, and so on.
In this file, change references to
localhost:8080
orlocalhost:8443
to the URL and port that WebLogic runs on, which by default should belocalhost:7001
.You also need to make the same change in the Azure app registration, where you set it in the Azure portal as the Redirect URI value on the Authentication tab.
Use the following steps to deploy the sample to WebLogic via the web console:
Start the WebLogic server with DOMAIN_NAME\bin\startWebLogic.cmd.
Navigate to the WebLogic web console in your browser at
http://localhost:7001/console
.Go to Domain Structure > Deployments, select Install, select Upload your files, and then find the .war file that you built using Maven.
Select Install this deployment as an application, select Next, select Finish, and then select Save.
Most of the default settings should be fine except that you should name the application to match the redirect URI you set in the sample configuration or Azure app registration. That is, if the redirect URI is
http://localhost:7001/msal4j-servlet-auth
, then you should name the applicationmsal4j-servlet-auth
.Go back to Domain Structure > Deployments, and start your application.
After the application starts, navigate to
http://localhost:7001/<application-name>/
, and you should be able to access the 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 in the Microsoft Entra ID tenant.
- On the consent screen, notice the scopes that are being requested.
- 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.
- Select Admins Only to view the
/admin_only
page. Only users with app rolePrivilegedAdmin
can view this page. Otherwise, an authorization failure message is displayed. - Select Regular Users to view the
/regular_user
page. Only users with app roleRegularUser
orPrivilegedAdmin
can view this page. Otherwise, an authorization failure message is displayed. - Use the button in the corner to sign out.
About the code
This sample uses MSAL for Java (MSAL4J) to sign a user in and obtain an ID token that might contain the roles claim. Based on the roles claim present, the signed-in user can access none, one, or both of the protected pages, Admins Only
and Regular Users
.
If you want to replicate this sample's behavior, you can copy the pom.xml file and the contents of the helpers and authservlets folders in the src/main/java/com/microsoft/azuresamples/msal4j folder. You also need the authentication.properties file. These classes and files contain generic code that you can use in a wide array of applications. You can copy the rest of the sample as well, but the other classes and files are built specifically to address this sample's objective.
Contents
The following table shows the contents of the sample project folder:
File/folder | Description |
---|---|
src/main/java/com/microsoft/azuresamples/msal4j/roles/ | This directory contains the classes that define the 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. |
Process a roles claim in the ID token
The roles claim of the token includes the names of the roles that the signed-in user is assigned to, as shown in the following example:
{
...
"roles": [
"Role1",
"Role2",]
...
}
ConfidentialClientApplication
A ConfidentialClientApplication
instance is created in the AuthHelper.java file, as shown in the following example. 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 are used for instantiation:
- The client ID of the app.
- The client secret, which is a requirement for Confidential Client Applications.
- The Microsoft Entra ID 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 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 on for your Microsoft Entra ID tenant. The MSAL4JConfidentialClientApplication
instance is used to construct an authorization request URL. The app redirects the browser to this URL, which is where the user signs 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);
The following list describes the features of this code:
AuthorizationRequestUrlParameters
: Parameters that must be set in order to build an AuthorizationRequestUrl.REDIRECT_URI
: Where Microsoft Entra ID redirects the browser - along with the auth code - after collecting user credentials. It must match the redirect URI in the Microsoft Entra ID app registration in the Azure portal.SCOPES
: Scopes are permissions requested by the application.- Normally, the three scopes
openid profile offline_access
suffice 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, such as
User.Read
.
- 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 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 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();
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. If the nonce check passes, the results are placed incontext
- an instance ofIdentityContextData
- and saved to the session. The application can then instantiate theIdentityContextData
from the session by way of an instance ofIdentityContextAdapterServlet
whenever it needs access to it, as shown in the following code:// 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());
Protect the routes
For information about how the sample app filters access to routes, see AuthenticationFilter.java. In the authentication.properties file, the app.protect.authenticated
property contains the comma-separated routes that only authenticated users can access, as shown in the following example:
# for example, /token_details requires any user to be signed in and does not require special roles claim(s)
app.protect.authenticated=/token_details
Any of the routes listed in the comma-separated rule sets under the app.protect.roles
are also off-limits to non-authenticated authenticated users, as shown in the following example. However, these routes also contain a space-separated list of app role memberships: only users having at least one of the corresponding roles can access these routes after authenticating.
# local short names for app roles - for example, sets admin to mean PrivilegedAdmin (useful for long rule sets defined in the next key, app.protect.roles)
app.roles=admin PrivilegedAdmin, user RegularUser
# A route and its corresponding <space-separated> role(s) that can access it; the start of the next route & its role(s) is delimited by a <comma-and-space-separator>
# this says: /admins_only can be accessed by PrivilegedAdmin, /regular_user can be accessed by PrivilegedAdmin role and the RegularUser role
app.protect.roles=/admin_only admin, /regular_user admin user
Scopes
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 sign-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
.
For the scopes requested by the application, see authentication.properties. These three scopes are requested by MSAL and given by Microsoft Entra ID by default.
More information
- Microsoft Authentication Library (MSAL) for Java
- Microsoft identity platform
- Quickstart: Register an application with the Microsoft identity platform
- Understanding Microsoft Entra ID application consent experiences
- Understand user and admin consent
- MSAL code samples
- How to: Add app roles to your application and receive them in the token
- Manage user assignment for an app in Microsoft Entra ID
Next step
Deploy Java WebLogic apps to WebLogic on Azure Virtual Machines