|
| 1 | +--- |
| 2 | +title: "Quickstart: Call Microsoft Graph from a Java daemon | Azure" |
| 3 | +titleSuffix: Microsoft identity platform |
| 4 | +description: In this quickstart, you learn how a Java app can get an access token and call an API protected by Microsoft identity platform endpoint, using the app's own identity |
| 5 | +services: active-directory |
| 6 | +author: mmacy |
| 7 | +manager: CelesteDG |
| 8 | +ms.service: active-directory |
| 9 | +ms.subservice: develop |
| 10 | +ms.topic: include |
| 11 | +ms.workload: identity |
| 12 | +ms.date: 01/10/2022 |
| 13 | +ms.author: marsma |
| 14 | +ms.custom: aaddev, "scenarios:getting-started", "languages:Java", devx-track-java, mode-other |
| 15 | +#Customer intent: As an application developer, I want to learn how my Java app can get an access token and call an API that's protected by Microsoft identity platform endpoint using client credentials flow. |
| 16 | +--- |
| 17 | + |
| 18 | +In this quickstart, you download and run a code sample that demonstrates how a Java application can get an access token using the app's identity to call the Microsoft Graph API and display a [list of users](/graph/api/user-list) in the directory. The code sample demonstrates how an unattended job or Windows service can run with an application identity, instead of a user's identity. |
| 19 | + |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +## Prerequisites |
| 24 | + |
| 25 | +To run this sample, you need: |
| 26 | + |
| 27 | +- [Java Development Kit (JDK)](https://openjdk.java.net/) 8 or greater |
| 28 | +- [Maven](https://maven.apache.org/) |
| 29 | + |
| 30 | + |
| 31 | +## Register and download your quickstart app |
| 32 | + |
| 33 | +You have two options to start your quickstart application: Express (Option 1 below), and Manual (Option 2) |
| 34 | + |
| 35 | +### Option 1: Register and auto configure your app and then download your code sample |
| 36 | + |
| 37 | +1. Go to the [Azure portal - App registrations](https://portal.azure.com/?Microsoft_AAD_RegisteredApps=true#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/JavaDaemonQuickstartPage/sourceType/docs) quickstart experience. |
| 38 | +1. Enter a name for your application and select **Register**. |
| 39 | +1. Follow the instructions to download and automatically configure your new application with just one click. |
| 40 | + |
| 41 | +### Option 2: Register and manually configure your application and code sample |
| 42 | + |
| 43 | +#### Step 1: Register your application |
| 44 | +To register your application and add the app's registration information to your solution manually, follow these steps: |
| 45 | + |
| 46 | +1. Sign in to the [Azure portal](https://portal.azure.com/). |
| 47 | +1. If you have access to multiple tenants, use the **Directories + subscriptions** filter :::image type="icon" source="../../media/common/portal-directory-subscription-filter.png" border="false"::: in the top menu to switch to the tenant in which you want to register the application. |
| 48 | +1. Search for and select **Azure Active Directory**. |
| 49 | +1. Under **Manage**, select **App registrations** > **New registration**. |
| 50 | +1. Enter a **Name** for your application, for example `Daemon-console`. Users of your app might see this name, and you can change it later. |
| 51 | +1. Select **Register**. |
| 52 | +1. Under **Manage**, select **Certificates & secrets**. |
| 53 | +1. Under **Client secrets**, select **New client secret**, enter a name, and then select **Add**. Record the secret value in a safe location for use in a later step. |
| 54 | +1. Under **Manage**, select **API Permissions** > **Add a permission**. Select **Microsoft Graph**. |
| 55 | +1. Select **Application permissions**. |
| 56 | +1. Under **User** node, select **User.Read.All**, then select **Add permissions**. |
| 57 | + |
| 58 | +#### Step 2: Download the Java project |
| 59 | +[Download the Java daemon project](https://github.com/Azure-Samples/ms-identity-java-daemon/archive/master.zip) |
| 60 | + |
| 61 | +#### Step 3: Configure the Java project |
| 62 | + |
| 63 | +1. Extract the zip file to a local folder close to the root of the disk, for example, *C:\Azure-Samples*. |
| 64 | +1. Navigate to the sub folder **msal-client-credential-secret**. |
| 65 | +1. Edit *src\main\resources\application.properties* and replace the values of the fields `AUTHORITY`, `CLIENT_ID`, and `SECRET` with the following snippet: |
| 66 | + |
| 67 | + ``` |
| 68 | + AUTHORITY=https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/ |
| 69 | + CLIENT_ID=Enter_the_Application_Id_Here |
| 70 | + SECRET=Enter_the_Client_Secret_Here |
| 71 | + ``` |
| 72 | + Where: |
| 73 | + - `Enter_the_Application_Id_Here` - is the **Application (client) ID** for the application you registered. |
| 74 | + - `Enter_the_Tenant_Id_Here` - replace this value with the **Tenant Id** or **Tenant name** (for example, contoso.microsoft.com). |
| 75 | + - `Enter_the_Client_Secret_Here` - replace this value with the client secret created on step 1. |
| 76 | + |
| 77 | +>[!TIP] |
| 78 | +>To find the values of **Application (client) ID**, **Directory (tenant) ID**, go to the app's **Overview** page in the Azure portal. To generate a new key, go to **Certificates & secrets** page. |
| 79 | +
|
| 80 | +#### Step 4: Admin consent |
| 81 | + |
| 82 | +If you try to run the application at this point, you'll receive *HTTP 403 - Forbidden* error: `Insufficient privileges to complete the operation`. This error happens because any *app-only permission* requires Admin consent: a global administrator of your directory must give consent to your application. Select one of the options below depending on your role: |
| 83 | + |
| 84 | +##### Global tenant administrator |
| 85 | + |
| 86 | + |
| 87 | +If you are a global tenant administrator, go to **API Permissions** page in **App registrations** in the Azure portal and select **Grant admin consent for {Tenant Name}** (Where {Tenant Name} is the name of your directory). |
| 88 | + |
| 89 | +##### Standard user |
| 90 | + |
| 91 | +If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. To do this, give the following URL to your administrator: |
| 92 | + |
| 93 | +```url |
| 94 | +https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here |
| 95 | +``` |
| 96 | + |
| 97 | + Where: |
| 98 | + * `Enter_the_Tenant_Id_Here` - replace this value with the **Tenant Id** or **Tenant name** (for example, contoso.microsoft.com) |
| 99 | + * `Enter_the_Application_Id_Here` - is the **Application (client) ID** for the application you registered. |
| 100 | + |
| 101 | + |
| 102 | +#### Step 5: Run the application |
| 103 | + |
| 104 | +You can test the sample directly by running the main method of ClientCredentialGrant.java from your IDE. |
| 105 | + |
| 106 | +From your shell or command line: |
| 107 | + |
| 108 | +``` |
| 109 | +$ mvn clean compile assembly:single |
| 110 | +``` |
| 111 | + |
| 112 | +This will generate a msal-client-credential-secret-1.0.0.jar file in your /targets directory. Run this using your Java executable like below: |
| 113 | + |
| 114 | +``` |
| 115 | +$ java -jar msal-client-credential-secret-1.0.0.jar |
| 116 | +``` |
| 117 | + |
| 118 | +After running, the application should display the list of users in the configured tenant. |
| 119 | + |
| 120 | +> [!IMPORTANT] |
| 121 | +> This quickstart application uses a client secret to identify itself as confidential client. Because the client secret is added as a plain-text to your project files, for security reasons, it is recommended that you use a certificate instead of a client secret before considering the application as production application. For more information on how to use a certificate, see [these instructions](https://github.com/Azure-Samples/ms-identity-java-daemon/tree/master/msal-client-credential-certificate) in the same GitHub repository for this sample, but in the second folder **msal-client-credential-certificate**. |
| 122 | +
|
| 123 | +## More information |
| 124 | + |
| 125 | +### MSAL Java |
| 126 | + |
| 127 | +[MSAL Java](https://github.com/AzureAD/microsoft-authentication-library-for-java) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. As described, this quickstart requests tokens by using the application own identity instead of delegated permissions. The authentication flow used in this case is known as *[client credentials oauth flow](../../v2-oauth2-client-creds-grant-flow.md)*. For more information on how to use MSAL Java with daemon apps, see [this article](../../scenario-daemon-overview.md). |
| 128 | + |
| 129 | +Add MSAL4J to your application by using Maven or Gradle to manage your dependencies by making the following changes to the application's pom.xml (Maven) or build.gradle (Gradle) file. |
| 130 | + |
| 131 | +In pom.xml: |
| 132 | + |
| 133 | +```xml |
| 134 | +<dependency> |
| 135 | + <groupId>com.microsoft.azure</groupId> |
| 136 | + <artifactId>msal4j</artifactId> |
| 137 | + <version>1.0.0</version> |
| 138 | +</dependency> |
| 139 | +``` |
| 140 | + |
| 141 | +In build.gradle: |
| 142 | + |
| 143 | +```$xslt |
| 144 | +compile group: 'com.microsoft.azure', name: 'msal4j', version: '1.0.0' |
| 145 | +``` |
| 146 | + |
| 147 | +### MSAL initialization |
| 148 | + |
| 149 | +Add a reference to MSAL for Java by adding the following code to the top of the file where you will be using MSAL4J: |
| 150 | + |
| 151 | +```Java |
| 152 | +import com.microsoft.aad.msal4j.*; |
| 153 | +``` |
| 154 | + |
| 155 | +Then, initialize MSAL using the following code: |
| 156 | + |
| 157 | +```Java |
| 158 | +IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET); |
| 159 | + |
| 160 | +ConfidentialClientApplication cca = |
| 161 | + ConfidentialClientApplication |
| 162 | + .builder(CLIENT_ID, credential) |
| 163 | + .authority(AUTHORITY) |
| 164 | + .build(); |
| 165 | +``` |
| 166 | + |
| 167 | +> | Where: |Description | |
| 168 | +> |---------|---------| |
| 169 | +> | `CLIENT_SECRET` | Is the client secret created for the application in Azure portal. | |
| 170 | +> | `CLIENT_ID` | Is the **Application (client) ID** for the application registered in the Azure portal. You can find this value in the app's **Overview** page in the Azure portal. | |
| 171 | +> | `AUTHORITY` | The STS endpoint for user to authenticate. Usually `https://login.microsoftonline.com/{tenant}` for public cloud, where {tenant} is the name of your tenant or your tenant Id.| |
| 172 | +
|
| 173 | +### Requesting tokens |
| 174 | + |
| 175 | +To request a token using app's identity, use `acquireToken` method: |
| 176 | + |
| 177 | +```Java |
| 178 | +IAuthenticationResult result; |
| 179 | + try { |
| 180 | + SilentParameters silentParameters = |
| 181 | + SilentParameters |
| 182 | + .builder(SCOPE) |
| 183 | + .build(); |
| 184 | + |
| 185 | + // try to acquire token silently. This call will fail since the token cache does not |
| 186 | + // have a token for the application you are requesting an access token for |
| 187 | + result = cca.acquireTokenSilently(silentParameters).join(); |
| 188 | + } catch (Exception ex) { |
| 189 | + if (ex.getCause() instanceof MsalException) { |
| 190 | + |
| 191 | + ClientCredentialParameters parameters = |
| 192 | + ClientCredentialParameters |
| 193 | + .builder(SCOPE) |
| 194 | + .build(); |
| 195 | + |
| 196 | + // Try to acquire a token. If successful, you should see |
| 197 | + // the token information printed out to console |
| 198 | + result = cca.acquireToken(parameters).join(); |
| 199 | + } else { |
| 200 | + // Handle other exceptions accordingly |
| 201 | + throw ex; |
| 202 | + } |
| 203 | + } |
| 204 | + return result; |
| 205 | +``` |
| 206 | + |
| 207 | +> |Where:| Description | |
| 208 | +> |---------|---------| |
| 209 | +> | `SCOPE` | Contains the scopes requested. For confidential clients, this should use the format similar to `{Application ID URI}/.default` to indicate that the scopes being requested are the ones statically defined in the app object set in the Azure portal (for Microsoft Graph, `{Application ID URI}` points to `https://graph.microsoft.com`). For custom web APIs, `{Application ID URI}` is defined under the **Expose an API** section in **App registrations** in the Azure portal.| |
| 210 | +
|
| 211 | +[!INCLUDE [Help and support](../../../../../includes/active-directory-develop-help-support-include.md)] |
| 212 | + |
| 213 | +## Next steps |
| 214 | + |
| 215 | +To learn more about daemon applications, see the scenario landing page. |
| 216 | + |
| 217 | +> [!div class="nextstepaction"] |
| 218 | +> [Daemon application that calls web APIs](../../scenario-daemon-overview.md) |
0 commit comments