### Start WebLogic Server
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Initiate the WebLogic server using the provided script. Access the WebLogic console to deploy the application.
```bash
DOMAIN_NAME/bin/startWebLogic.cmd
```
--------------------------------
### Deploy to Tomcat
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Copy the generated .war file to Tomcat's /webapps/ directory and start the server. Access the application via the configured URL.
```bash
cp your-sample.war /path/to/tomcat/webapps/
```
--------------------------------
### Install Maven Project
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Maven
Install the packaged Maven project locally, skipping integration tests.
```bash
mvn install -DskipITs
```
--------------------------------
### Example Instance Discovery JSON Response
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Instance-Discovery
This is an example of the JSON response received when making an HTTP GET request to the instance discovery endpoint. It contains tenant discovery details and metadata for various network endpoints.
```json
{
"tenant_discovery_endpoint": "https://login.microsoftonline.com/common/.well-known/openid-configuration",
"api-version": "1.1",
"metadata": [
{
"preferred_network": "login.microsoftonline.com",
"preferred_cache": "login.windows.net",
"aliases": [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net"
]
},
{
"preferred_network": "login.partner.microsoftonline.cn",
"preferred_cache": "login.partner.microsoftonline.cn",
"aliases": [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn"
]
},
{
"preferred_network": "login.microsoftonline.de",
"preferred_cache": "login.microsoftonline.de",
"aliases": [
"login.microsoftonline.de"
]
},
{
"preferred_network": "login.microsoftonline.us",
"preferred_cache": "login.microsoftonline.us",
"aliases": [
"login.microsoftonline.us",
"login.usgovcloudapi.net"
]
},
{
"preferred_network": "login-us.microsoftonline.com",
"preferred_cache": "login-us.microsoftonline.com",
"aliases": [
"login-us.microsoftonline.com"
]
}
]
}
```
--------------------------------
### Clone and Build Maven Project
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Maven
Clone the repository and use Maven to clean and package the project. Ensure Java and Maven are installed.
```bash
git clone https://github.com/AzureAD/microsoft-authentication-library-for-java.git
```
```bash
cd microsoft-authentication-library-for-java
```
```bash
mvn clean
```
```bash
mvn package
```
--------------------------------
### Implement Custom HTTP Client with OkHttpClientAdapter
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Configure-Http-Client
Implement the `IHttpClient` interface to create a custom HTTP client. This example shows how to adapt OkHttpClient, mapping MSAL's HttpRequest to OkHttpClient's Request and OkHttpClient's Response to MSAL's IHttpResponse.
```Java
class OkHttpClientAdapter implements IHttpClient{
private OkHttpClient client;
OkHttpClientAdapter(){
// You can configure OkHttpClient
this.client = new OkHttpClient();
}
@Override
public IHttpResponse send(HttpRequest httpRequest) throws IOException {
// Map URL, headers, and body from MSAL's HttpRequest to OkHttpClient request object
Request request = buildOkRequestFromMsalRequest(httpRequest);
// Execute Http request with OkHttpClient
Response okHttpResponse= client.newCall(request).execute();
// Map status code, headers, and response body from OkHttpClient's Response object to MSAL's IHttpResponse
return buildMsalResponseFromOkResponse(okHttpResponse);
}
}
```
--------------------------------
### Configure Logback for MSAL Debug Logs
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Logging
Create a logback.xml file in your classpath to configure logback. This example sets up console output for all MSAL Java debug logs.
```xml
%d{HH:mm:5.5} [%thread] %-5level %logger{36} - %msg%n
```
--------------------------------
### Example Telemetry Event - HTTP
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Telemetry
An example of a telemetry event detailing a successful call to the token endpoint, including request details and response codes.
```text
Event Name: msal.http_event
start_time=1691604456963
msal.http_path=https://login.microsoftonline.com//oauth2/v2.0/token
msal.request_id_header=0ab7d6cc-e0a9-48e7-bab0-83c82ed60e01
msal.server_error_code=0
msal.token_age=
elapsed_time=789
msal.http_method=POST
event_name=msal.http_event
msal.server_sub_error_code=0
msal.response_code=200
```
--------------------------------
### Get Accounts from MSAL Java Application
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Migrate-to-MSAL-Java
Retrieve the accounts currently signed in to the MSAL Java application. This is useful for subsequent token acquisition operations.
```java
Set accounts = app.getAccounts().join();
```
--------------------------------
### Deploy Sample to WebLogic
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Deploy the .war file through the WebLogic web console. Name the application to match the Redirect URI configured in your sample and Azure app registration.
```bash
http://localhost:7001/console
```
--------------------------------
### Build .war File with Maven
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Use this Maven command to clean and package your MSAL Java sample into a .war file for deployment.
```bash
mvn clean package
```
--------------------------------
### Initialize MSAL4J Client with Instance Discovery Metadata
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Instance-Discovery
This Java code demonstrates how to initialize a PublicClientApplication using pre-fetched instance discovery metadata. Ensure the provided JSON string is valid.
```java
String instanceDiscoveryResponse = readResource(
"/aad_instance_discovery_response.json");
PublicClientApplication app = PublicClientApplication.builder("client_id")
.instanceDiscoveryMetadata(instanceDiscoveryResponse)
.build();
```
--------------------------------
### Initialize PublicClientApplication with PII Logging Enabled
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Logging
Enable PII or OII logging by calling .logPii(true) during the PublicClientApplication builder configuration. The application is then responsible for handling sensitive data.
```java
PublicClientApplication app2 = PublicClientApplication.builder(PUBLIC_CLIENT_ID)
.authority(AUTHORITY)
.logPii(true)
.build();
```
--------------------------------
### Initialize PublicClientApplication with PII Logging Disabled
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Logging
This code snippet shows how to build a PublicClientApplication instance when PII or OII logging is disabled, which is the default behavior.
```java
PublicClientApplication app2 = PublicClientApplication.builder(PUBLIC_CLIENT_ID)
.authority(AUTHORITY)
.build();
```
--------------------------------
### Create and Configure Broker for WAM in MSAL Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Using-Web-Account-Manager-with-MSAL-Java
Instantiate a `Broker` object, specifying support for Windows, and then pass it to the `PublicClientApplication` builder. This enables MSAL Java to use WAM for authentication when running on a Windows OS.
```java
IBroker broker = new Broker.Builder().supportWindows(true).build();
PublicClientApplication pca = PublicClientApplication.builder(clientId)
.authority(authority)
.broker(broker) //Add the broker when creating your PublicClientApplication
.build();
```
--------------------------------
### Instantiate Public Client Application with MSAL4J
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Applications
Use this when creating a public client application. Ensure you have the client ID and authority configured.
```java
String PUBLIC_CLIENT_ID;
String AUTHORITY;
PublicClientApplication app =
PublicClientApplication
.builder(PUBLIC_CLIENT_ID)
.authority(AUTHORITY)
.build();
```
--------------------------------
### Instantiate Confidential Client Application with Certificate
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Applications
Use this for confidential client applications when you have a certificate. This requires the client ID, a credential created from the private key and public certificate, and the authority.
```java
String PUBLIC_CLIENT_ID;
String AUTHORITY;
PrivateKey PRIVATE_KEY;
X509Certificate PUBLIC_KEY;
IClientCredential credential = ClientCredentialFactory.createFromCertificate(PRIVATE_KEY, PUBLIC_KEY);
ConfidentialClientApplication app =
ConfidentialClientApplication
.builder(PUBLIC_CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
```
--------------------------------
### Create Client Credential with Certificate (Private and Public Keys)
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Credentials
Use this when your confidential client application uses a certificate. Pass the private and public keys to ClientCredentialFactory.create().
```java
PrivateKey privateKey;
X509Certificate publicKey;
IClientCredential credential = ClientCredentialFactory.create(privateKey, publicKey)
```
--------------------------------
### Access Deployed WebLogic Application
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Navigate to the application's URL in your browser after successful deployment and startup in WebLogic.
```bash
http://localhost:7001/{your-application-name}/
```
--------------------------------
### Acquire Token Silently or Interactively with MSAL4J
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Acquiring-Tokens
This code demonstrates the recommended pattern for acquiring tokens. It first attempts to acquire a token silently using `acquireTokenSilently`. If that fails, it falls back to an interactive flow using `acquireToken` to obtain a new token. Ensure you handle exceptions appropriately and replace placeholder values like `someScopes` and `new URI("http://localhost")` with your actual requirements.
```Java
//...\n//In some other part of your code, make the client application (public or confidential).\n//This object will have an in-memory cache associated with it, \n// and the cache will exist for as long as the public/confidential client app object does\nPublicClientApplication pca = new PublicCLientApplication.builder(...);\n//...\n\n\n//In some method for acquiring a token....\npublic IAuthenticationResult getAToken(PublicClientApplication pca) {\n //Get the account you want to retrieve a token for\n //Doing this outside of this method is probably more efficient, as you can re-use the list of accounts for multiple calls\n Set accountsInCache = pca.getAccounts().join();\n //Filter the accounts in some way (this example just uses the first one in the list for simplicity)\n IAccount account = accountsInCache.iterator().next();\n\n IAuthenticationResult result;\n try {\n //Build the SilentParameters object using the account you want to get the token for,\n // and the scopes you want the token to have\n SilentParameters silentParameters =\n SilentParameters\n .builder(someScopes, account)\n .build();\n\n //Try to acquire the token silently. This will either return a cached token for the account/scopes\n // defined in the silentParameters object, or it will cause an exception saying their was no cached token\n result = pca.acquireTokenSilently(silentParameters).join();\n } catch (Exception ex) {\n //If an MsalException is thrown, something went wrong with the silent call and you should try another flow\n if (ex.getCause() instanceof MsalException) {\n //(interactive flow used here just as an example, swap this out with your preferred flow)\n //Build the InteractiveRequestParameters using the scopes you want the token to have\n InteractiveRequestParameters parameters = InteractiveRequestParameters\n .builder(new URI("http://localhost"))\n .scopes(someScopes)\n .build();\n\n //Try to acquire a brand new token\n result = pca.acquireToken(parameters).join();\n } else {\n // Handle other exceptions accordingly\n throw ex;\n }\n }\n return result;\n}
```
--------------------------------
### Instantiate Confidential Client Application with Secret
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Applications
Use this for confidential client applications when you have a client secret. This requires the client ID, a credential created from the secret, and the authority.
```java
String PUBLIC_CLIENT_ID;
String AUTHORITY;
String CLIENT_SECRET;
IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
ConfidentialClientApplication app =
ConfidentialClientApplication
.builder(PUBLIC_CLIENT_ID, credential)
.authority(AUTHORITY)
.build();
```
--------------------------------
### Run Maven Tests
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Maven
Execute the test suite for the Maven project.
```bash
mvn test
```
--------------------------------
### Instantiate PublicClientApplication for B2C
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/AAD-B2C-specifics
Use this when initializing a public client application with a B2C authority. Ensure the B2C_AUTHORITY constant is correctly set.
```java
PublicClientApplication pca = new PublicClientApplication.Builder(APP_ID)
.b2cAuthority(B2C_AUTHORITY)
.build();
```
--------------------------------
### Implement Custom Browser Opening Logic
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Acquiring-Token-Interactively
Customize the browser opening behavior by implementing the `OpenBrowserAction` interface and providing your own logic within the `openBrowser` method. Pass this custom action to `SystemBrowserOptions`.
```java
class CustomOpenBrowserAction implements OpenBrowserAction {
@Override
public void openBrowser(URL url){
//Custom logic to open URL
}
}
SystemBrowserOptions options =
SystemBrowserOptions
.builder()
.openBrowserAction(new CustomOpenBrowserAction())
.build();
```
--------------------------------
### Create Keystore for Fiddler
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Fiddler
Use the keytool command to import the FiddlerRoot.cer certificate into a keystore file. This is necessary for Fiddler to decrypt and inspect SSL/TLS traffic.
```bash
\bin\keytool.exe -import -file C:\Users\\Desktop\FiddlerRoot.cer\
-keystore FiddlerKeystore -alias Fiddler
```
--------------------------------
### Acquire Token Interactively using System Browser
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Acquiring-Token-Interactively
Use this code to initiate an interactive token acquisition flow using the system browser. Ensure `http://localhost` or a specific port is configured as a redirect URI in your app registration.
```java
PublicClientApplication publicClientApplication =
PublicClientApplication
.builder(CLIENT_ID)
.authority(AUTHORITY)
.build();
InteractiveRequestParameters parameters = InteractiveRequestParameters
.builder(new URI("http://localhost"))
.scopes(scope)
.build();
IAuthenticationResult result = publicClientApplication.acquireToken(parameters).join();
```
--------------------------------
### Configure PersistenceSettings for Token Cache
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/msal4j-persistence-extension/README.md
Configure persistence settings, including cache file path and platform-specific keychain/keyring details. This method sets up parameters for Windows, Mac, and Linux environments.
```java
private PersistenceSettings createPersistenceSettings() throws IOException {
Path path = Paths.get(System.getProperty("user.home"), "MSAL", "testCache");
return PersistenceSettings.builder("testCacheFile", path)
.setMacKeychain("MsalTestService", "MsalTestAccount")
.setLinuxKeyring(null,
"MsalTestSchema",
"MsalTestSecretLabel",
"MsalTestAttribute1Key",
"MsalTestAttribute1Value",
"MsalTestAttribute2Key",
"MsalTestAttribute2Value")
.setLockRetry(1000, 50)
.build();
}
```
--------------------------------
### ADAL4J vs. MSAL4J Token Acquisition Methods
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Migrate-to-MSAL-Java
Compares the methods used in ADAL4J and MSAL4J for acquiring tokens. MSAL4J uses parameters like ClientCredentialParameters, UsernamePasswordParameters, and SilentParameters, while ADAL4J relied on resource strings and credentials.
```java
acquireToken(String resource, ClientCredential credential, AuthenticationCallback callback)
```
```java
acquireToken(ClientCredentialParameters)
```
```java
acquireToken(String resource, ClientAssertion assertion, AuthenticationCallback callback)
```
```java
acquireToken(ClientCredentialParameters)
```
```java
acquireToken(String resource, AsymmetricKeyCredential credential, AuthenticationCallback callback)
```
```java
acquireToken(ClientCredentialParameters)
```
```java
acquireToken(String resource, String clientId, String username, String password, AuthenticationCallback callback)
```
```java
acquireToken(UsernamePasswordParameters)
```
```java
acquireToken(String resource, String clientId, String username, String password=null, AuthenticationCallback callback)
```
```java
acquireToken(IntegratedWindowsAuthenticationParameters)
```
```java
acquireToken(String resource, UserAssertion userAssertion, ClientCredential credential, AuthenticationCallback callback)
```
```java
acquireToken(OnBehalfOfParameters)
```
```java
acquireTokenByAuthorizationCode()
```
```java
acquireToken(AuthorizationCodeParameters)
```
```java
acquireDeviceCode() and acquireTokenByDeviceCode()
```
```java
acquireToken(DeviceCodeParameters)
```
```java
acquireTokenByRefreshToken()
```
```java
acquireTokenSilently(SilentParameters)
```
--------------------------------
### Acquire Token using Device Code Flow in Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Device-Code-Flow
Use this snippet to initiate the device code flow. It prints the user code and prompts for authentication on another device. The result is handled asynchronously.
```java
PublicClientApplication app = PublicClientApplication.builder(PUBLIC_CLIENT_ID)
.authority(AUTHORITY)
.build();
Consumer deviceCodeConsumer = (DeviceCode deviceCode) -> {
System.out.println(deviceCode.message());
};
CompletableFuture future = app.acquireToken(
DeviceCodeFlowParameters.builder(scope, deviceCodeConsumer).build());
future.handle((res, ex) -> {
if(ex != null) {
System.out.println("message - " + ex.getMessage());
return "Unknown!";
}
System.out.println("Access Token - " + res.accessToken());
System.out.println("ID Token - " + res.idToken());
return res;
});
future.join();
```
--------------------------------
### Instantiate ConfidentialClientApplication for B2C
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/AAD-B2C-specifics
Use this when initializing a confidential client application with a B2C authority. Ensure the B2C_AUTHORITY constant is correctly set.
```java
ConfidentialClientApplication cca = ConfidentialClientApplication.builder(APP_ID, credential)
.b2cAuthority(B2C_AUTHORITY)
.build();
```
--------------------------------
### Build Confidential Client Application
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Credentials
After creating the IClientCredential, use it to build a ConfidentialClientApplication. Ensure CLIENT_ID is defined.
```java
ConfidentialClientApplication app =
ConfidentialClientApplication.builder(
CLIENT_ID,
credential)
.build();
```
--------------------------------
### Acquire Token with Username and Password (Java)
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Acquiring-Tokens-with-username-and-password
This snippet demonstrates how to use the username and password flow to acquire an authentication token using ADAL4J. It requires setting up the application ID, authority, username, password, and scopes. Note that this flow is less secure and may not work with conditional access policies.
```java
final String AUTHORITY;
final String APP_ID;
String userName;
String password;
List scopes;
PublicClientApplication pca = new PublicClientApplication.Builder(APP_ID).
authority(AUTHORITY).
build();
UserNamePasswordParameters paramaters =
UserNamePasswordParameters.builder(
scopes,
userName,
password.toCharArray()).build();
IAuthenticationResult result = pca.acquireToken(parameters).get();
```
--------------------------------
### Configure IntelliJ for Fiddler Proxy
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Fiddler
Set up IntelliJ's run/debug configurations to use Fiddler as a proxy. This involves specifying proxy host, port, and the trust store for SSL certificates.
```java
-DproxySet=true
-DproxyHost=127.0.0.1
-DproxyPort=8888
-Djavax.net.ssl.trustStorePassword="yourpassword"
-Djavax.net.ssl.trustStore="path\to\keystore\FiddlerKeystore"
```
--------------------------------
### Create Client Credential with Certificate (PKCS12 InputStream)
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Credentials
Use this when your confidential client application uses a certificate stored in a PKCS12 format. Pass the InputStream and password to ClientCredentialFactory.create().
```java
InputStream inputStream;
String password;
IClientCredential credential = ClientCredentialFactory.create(inputStream, password)
```
--------------------------------
### Configure Tomcat Connector
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Ensure a entry exists in tomcat/conf/server.xml for your desired hosting address. Samples typically expect http://localhost:8080 or https://localhost:8443.
```xml
...
```
--------------------------------
### Enable Broker Logging in MSAL Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Using-Web-Account-Manager-with-MSAL-Java
Use this to allow MSAL Java to forward all logs from WAM. This is primarily helpful for debugging.
```java
Broker broker = ...;
//Allow MSAL to forward all logs from WAM
broker.enableBrokerLogging(true);
//Allow PII to appear in WAM logs
broker.enableBrokerPIILogging(true);
```
--------------------------------
### Create Client Credential with Application Secret
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Client-Credentials
Use this when your confidential client application has an application secret. Pass the secret string to ClientCredentialFactory.create().
```java
String CLIENT_SECRET;
IClientCredential credential = ClientCredentialFactory.create(CLIENT_SECRET)
```
--------------------------------
### Configure WebLogic Properties
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Deployment-Instructions-for-MSAL-Java-Samples
Update the application.properties or authentication.properties file in your sample to reflect WebLogic's default URL and port (localhost:7001).
```properties
app.homePage=http://localhost:7001/your-app-name
```
--------------------------------
### Configure MSAL Client with Persistence Aspect
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/msal4j-persistence-extension/README.md
Build a PublicClientApplication using MSAL Java, integrating the PersistenceTokenCacheAccessAspect for secure token cache management. This ensures that the token cache is persisted across application runs.
```java
return PublicClientApplication.builder(PUBLIC_CLIENT_ID)
.authority(AUTHORITY)
.setTokenCacheAccessAspect(createPersistenceAspect())
.build();
```
--------------------------------
### Set Custom HTTP Client on PublicClientApplication
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Configure-Http-Client
After implementing your custom HTTP client, set it on the PublicClientApplication builder. All subsequent HTTP requests made by MSAL will use this custom client.
```Java
IHttpClient httpClient = new OkHttpClientAdapter();
PublicClientApplication pca = PublicClientApplication.builder(
APP_ID).
authority(AUTHORITY).
httpClient(httpClient).
build();
```
--------------------------------
### Acquire Token using Authorization Code
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Acquiring-Tokens-with-Authorization-codes
Use this snippet to acquire an authentication result by providing the authorization code and reply URL. Ensure the necessary scopes are included.
```java
PublicClientApplication pca = new PublicClientApplication.Builder(APP_ID)
.authority(AUTHORITY)
.build();
IAuthenticationResult result = pca.acquireToken(AuthorizationCodeParameters
.builder(authCode, new URI(REPLY_URL))
.scopes(scope)
.build())
.get();
```
--------------------------------
### Handle MSAL Exceptions in Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Exceptions
This snippet demonstrates how to catch and differentiate between general exceptions and MsalInteractionRequiredException when acquiring tokens silently. If an MsalInteractionRequiredException is caught, it indicates that interactive authentication is necessary.
```java
IAuthenticationResult result;
try {
PublicClientApplication application = PublicClientApplication
.builder("clientId")
.b2cAuthority("authority")
.build();
SilentParameters parameters = SilentParameters
.builder(Collections.singleton("scope"))
.build();
result = application.acquireTokenSilently(parameters).join();
}
catch (Exception ex){
if(ex instanceof MsalInteractionRequiredException){
// AcquireToken by either AuthorizationCodeParameters or DeviceCodeParameters
} else{
// Log and handle exception accordingly
}
}
```
--------------------------------
### Configure Eclipse for Fiddler Proxy
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Fiddler
Configure Eclipse's run configurations to route traffic through Fiddler. This requires setting JVM arguments for proxy host, port, and trust store location.
```java
-DproxySet=true
-DproxyHost=127.0.0.1
-DproxyPort=8888
-Djavax.net.ssl.trustStore="path\to\keystore\FiddlerKeystore"
-Djavax.net.ssl.trustStorePassword="yourpassword"
```
--------------------------------
### Define Telemetry Consumer - Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Telemetry
Define a class with a consumer to process telemetry events. Telemetry events are received as a List of HashMaps.
```java
public class Telemetry {
private static List> eventsReceived = new ArrayList<>();
public static class MyTelemetryConsumer {
Consumer>> telemetryConsumer =
(List> telemetryEvents) -> {
eventsReceived.addAll(telemetryEvents);
System.out.println("Received " + telemetryEvents.size() + " events");
telemetryEvents.forEach(event -> {
System.out.print("Event Name: " + event.get("event_name"));
event.entrySet().forEach(entry -> System.out.println(" " + entry));
});
};
}
}
```
--------------------------------
### Add msal4j-persistence-extension Dependency
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/msal4j-persistence-extension/README.md
Add this dependency to your Maven pom.xml file to include the persistence extension library.
```xml
com.microsoft.azure
msal4j-persistence-extension
1.2.0
```
--------------------------------
### Add Logback Dependency to Maven POM
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Logging
Include this dependency in your pom.xml to use logback as your logging framework with MSAL for Java.
```xml
ch.qos.logback
logback-classic
1.2.3
```
--------------------------------
### Check Accounts in MSAL4J Token Cache
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Token-Cache
Call `PublicClientApplication.getAccounts()` to retrieve all accounts currently stored in the token cache. This is useful for understanding the cache's state.
```Java
PublicClientApplication pca = new PublicClientApplication.Builder(
labResponse.getAppId()).
authority(TestConstants.ORGANIZATIONS_AUTHORITY).
build();
Set accounts = pca.getAccounts().join();
```
--------------------------------
### Create PersistenceTokenCacheAccessAspect
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/msal4j-persistence-extension/README.md
Instantiate the PersistenceTokenCacheAccessAspect, which implements the ITokenCacheAccessAspect interface for MSAL Java. This aspect handles token cache serialization and persistence.
```java
private ITokenCacheAccessAspect createPersistenceAspect() throws IOException {
return new PersistenceTokenCacheAccessAspect(createPersistenceSettings());
}
```
--------------------------------
### Add MSAL4J Brokers Gradle Dependency
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/msal4j-brokers/README.md
Use this Gradle snippet in your build.gradle file to include the MSAL4J Brokers library.
```gradle
implementation group: 'com.microsoft.azure', name: 'msal4j-brokers', version: '0.0.1'
```
--------------------------------
### Acquire Token Silently with IWA using MSAL Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Integrated-Windows-Authentication
Use this code to acquire an authentication token silently using Integrated Windows Authentication. Ensure the application is running on a Windows domain-joined machine and that the user has previously consented to the application's use.
```java
final String AUTHORITY;
final String APP_ID;
String userName;
List scopes;
PublicClientApplication app = PublicClientApplication.builder(APP_ID)
.authority(AUTHORITY)
.build();
IntegratedWindowsAuthenticationParameters parameters =
IntegratedWindowsAuthenticationParameters.builder(scope, userName).build();
IAuthenticationResult future = app.acquireToken(parameters).get();
```
--------------------------------
### Register Telemetry Consumer - Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Telemetry
Register the defined telemetry consumer with the PublicClientApplication builder. This enables the application to receive telemetry events.
```java
PublicClientApplication app = PublicClientApplication.builder(APP_ID)
.authority(AUTHORITY)
.telemetryConsumer(new MyTelemetryConsumer().telemetryConsumer)
.build();
```
--------------------------------
### Custom Token Cache Serialization in MSAL4J
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Token-Cache
Implement `ITokenCacheAccessAspect` to customize token cache serialization and deserialization for persistent storage. Override `beforeCacheAccess` to load the cache and `afterCacheAccess` to save it.
```Java
static class TokenPersistence implements ITokenCacheAccessAspect{
String data;
TokenPersistence(String data){
this.data = data;
}
@Override
public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext){
iTokenCacheAccessContext.tokenCache().deserialize(data);
}
@Override
public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
data = iTokenCacheAccessContext.tokenCache().serialize();
}
}
```
```Java
// Loads cache from file
String dataToInitCache = readResource(this.getClass(), "/cache_data/serialized_cache.json");
ITokenCacheAccessAspect persistenceAspect = new TokenPersistence(dataToInitCache);
// By setting *TokenPersistence* on the PublicClientApplication, MSAL will call *beforeCacheAccess()* before accessing the cache and *afterCacheAccess()* after accessing the cache.
PublicClientApplication app =
PublicClientApplication.builder("my_client_id").setTokenCacheAccessAspect(persistenceAspect).build();
```
--------------------------------
### Acquire Token using On Behalf Of Flow
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Service-to-service-calls-on-behalf-of-the-user
Use this code when a web API needs to call another web API on behalf of a user. It requires the MSAL library for Java and involves creating a confidential client application and a user assertion.
```java
ConfidentialClientApplication cca =
ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.create(CLIENT_SECRET)).
authority(AUTHORITY).
build();
// Create an UserAssertion with the access token received from the client application
UserAssertion userAssertion = new UserAssertion(accessToken);
AuthenticationResult result =
cca.acquireToken(
OnBehalfOfParameters.builder(
Scope,
userAssertion).
build()).
get();
```
--------------------------------
### Build Authorization Request URL with MSAL4J
Source: https://github.com/azuread/microsoft-authentication-library-for-java/wiki/Authorization-Code-URL-Builder
Use this helper method to craft the authorization code URL for the OAuth2 authorization code flow. Ensure you have initialized PublicClientApplication or ConfidentialClientApplication.
```java
PublicClientApplication publicClientApplication =
PublicClientApplication
.builder(CLIENT_ID)
.authority(AUTHORITY)
.build();
AuthorizationRequestUrlParameters parameters =
AuthorizationRequestUrlParameters
.builder(interactiveRequestParameters.redirectUri().toString(),
interactiveRequestParameters.scopes())
.codeChallenge(verifier)
.codeChallengeMethod("S256")
.state(state);
.build();
URL authorizationCodeUrl = publicClientApplication.getAuthorizationRequestUrl(parameters);
```
--------------------------------
### Gradle Dependency for MSAL Java
Source: https://github.com/azuread/microsoft-authentication-library-for-java/blob/dev/README.md
Add this dependency to your Gradle project to include the MSAL Java library.
```gradle
implementation group: 'com.microsoft.azure', name: 'com.microsoft.aad.msal4j', version: '1.25.0'
```