Enable Java WebLogic apps to sign in users and access Microsoft Graph

This article demonstrates a Java WebLogic app that signs in users and obtains an access token for calling Microsoft Graph. It uses the Microsoft Authentication Library (MSAL) for Java.

The following diagram shows the topology of the app:

Diagram that shows the topology of the app.

The client app uses MSAL for Java (MSAL4J) to sign in a user and obtain an access token for Microsoft Graph from Microsoft Entra ID. The access token proves that the user is authorized to access the Microsoft Graph API endpoint as defined in the scope.

Prerequisites

  • Java 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.
  • A user account in any organization's Microsoft Entra ID tenant if you want to work with accounts in any organizational directory - that is, multi-tenant mode. This sample must be modified to work with a personal Microsoft account. 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.
  • A personal Microsoft account - for example, Xbox, Hotmail, Live, and so on - if you want to work with personal Microsoft accounts.

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-java-servlet-webapp-authentication.git
cd 2-Authorization-I/call-graph

Alternatively, navigate to the ms-identity-java-servlet-webapp-authentication 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. To register the app on the Azure portal, you can either follow manual configuration steps or use a PowerShell script. The script does the following tasks:

  • Creates the Microsoft Entra ID applications and related objects, such as passwords, permissions, and dependencies.
  • Modifies the project configuration files.
  • By default, sets up an application that works with accounts in your organizational directory only.

Use the following steps to run the PowerShell script:

  1. On Windows, open PowerShell and navigate to the root of the cloned directory.

  2. Use the following command to set the execution policy for PowerShell:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
    
  3. Use the following commands to run the configuration script:

    cd .\AppCreationScripts\
    .\Configure.ps1
    

    Note

    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.

Configure the app (java-servlet-webapp-call-graph) 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.

  1. Open the project in your IDE.

  2. Open the ./src/main/resources/authentication.properties file.

  3. Find the string {enter-your-tenant-id-here}. Replace the existing value with one of the following values:

    • Your Microsoft Entra ID tenant ID if you registered your app with the Accounts in this organizational directory only option.
    • The word organizations if you registered your app with the Accounts in any organizational directory option.
    • The word common if you registered your app with the Accounts in any organizational directory and personal Microsoft accounts option.
    • The word consumers if you registered your app with the Personal Microsoft accounts option.
  4. Find the string {enter-your-client-id-here} and replace the existing value with the application ID or clientId of the java-servlet-webapp-call-graph application copied from the Azure portal.

  5. Find the string {enter-your-client-secret-here} and replace the existing value with the value you saved during the creation of the java-servlet-webapp-call-graph app, 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 a variety of 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:

  1. In the sample, find the application.properties or authentication.properties file where you configured the client ID, tenant, redirect URL, and so on.

  2. In this file, change references to localhost:8080 or localhost:8443 to the URL and port that WebLogic runs on, which by default should be localhost:7001.

  3. 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:

  1. Start the WebLogic server with DOMAIN_NAME\bin\startWebLogic.cmd.

  2. Navigate to the WebLogic web console in your browser at http://localhost:7001/console.

  3. Go to Domain Structure > Deployments, select Install, select Upload your files, and then find the .war file that you built using Maven.

  4. Select Install this deployment as an application, select Next, select Finish, and then select Save.

  5. 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 application msal4j-servlet-auth.

  6. Go back to Domain Structure > Deployments, and start your application.

  7. 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:

  1. Notice the signed-in or signed-out status displayed at the center of the screen.
  2. Select the context-sensitive button in the corner. This button reads Sign In when you first run the app.
  3. On the next page, follow the instructions and sign in with an account in the Microsoft Entra ID tenant.
  4. On the consent screen, notice the scopes that are being requested.
  5. Notice that the context-sensitive button now says Sign out and displays your username.
  6. Select ID Token Details to see some of the ID token's decoded claims.
  7. Select Call Graph to make a call to Microsoft Graph's /me endpoint and see a selection of the user details obtained.
  8. 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 a token for Microsoft Graph API. It uses Microsoft Graph SDK for Java to obtain data from Graph. You must add these libraries to your projects using Maven.

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
AppCreationScripts/ Scripts to automatically configure Microsoft Entra ID app registrations.
src/main/java/com/microsoft/azuresamples/msal4j/callgraphwebapp/ 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.

ConfidentialClientApplication

A ConfidentialClientApplication instance is created in the AuthHelper.java file, as shown in the following example. This object helps craft the Microsoft Entra ID 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:

  1. 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 MSAL4J ConfidentialClientApplication 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 like User.Read and so on.
  2. 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 contain an authorization code.

  3. 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.
  4. If acquireToken is successful, the token claims are extracted. If the nonce check passes, the results are placed in context - an instance of IdentityContextData - and saved to the session. The application can then instantiate the IdentityContextData from the session by way of an instance of IdentityContextAdapterServlet 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 or groups claim(s)
app.protect.authenticated=/token_details, /call_graph

Call graph

When the user navigates to /call_graph, the application creates an instance of the IGraphServiceClient - from the Java Graph SDK - passing along the signed-in user's access token. The Graph client places the access token in the Authorization headers of its requests. The app then asks the Graph client to call the /me endpoint to yield details for the currently signed-in user.

The following code is all that's required for an application developer to write for accessing the /me endpoint, provided that they already have a valid access token for Graph Service with the User.Read scope.

//CallGraphServlet.java
User user = GraphHelper.getGraphClient(contextAdapter).me().buildRequest().get();

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. By default, the application sets the scopes value to User.Read. This particular Microsoft Graph API scope is for accessing the information of the current signed-in user. The graph endpoint for accessing this info is https://graph.microsoft.com/v1.0/me. Any valid requests made to this endpoint must bear an access_token that contains the scope User.Read in the Authorization header.

More information

Next step

Deploy Java WebLogic apps to WebLogic on Azure Virtual Machines