From 450757afc5dad60c723b44853e1c4227c34df105 Mon Sep 17 00:00:00 2001 From: Avery-Dunn <62066438+Avery-Dunn@users.noreply.github.com> Date: Thu, 5 Oct 2023 11:09:55 -0700 Subject: [PATCH] MSI Refactoring (#715) * Refactor the Application class hierarchy to better separate Public/ConfidentialClientApplication and ManagedIdentityApplication * Refactor ManagedIdentity classes to better follow Java best-practices, reduce use of public scope, and generally match the library's existing code styles * Merge cloud shell changes * Address code review comments * Move instance discovery and region fields back into AbstractClientApplicationBase only * Better grouping of public vs. non-public APIs --- .../msal4j/AadInstanceDiscoveryProvider.java | 25 +- .../aad/msal4j/AbstractApplicationBase.java | 352 ++++++++++++++++++ .../msal4j/AbstractClientApplicationBase.java | 293 +-------------- .../AcquireTokenByAppProviderSupplier.java | 2 +- ...uireTokenByAuthorizationGrantSupplier.java | 10 +- ...cquireTokenByClientCredentialSupplier.java | 2 +- .../AcquireTokenByDeviceCodeFlowSupplier.java | 2 +- ...AcquireTokenByManagedIdentitySupplier.java | 2 +- .../msal4j/AcquireTokenSilentSupplier.java | 12 +- .../AppServiceManagedIdentitySource.java | 4 +- .../msal4j/AuthenticationResultSupplier.java | 12 +- .../CloudShellManagedIdentitySource.java | 8 +- .../aad/msal4j/IApplicationBase.java | 46 +++ .../aad/msal4j/IClientApplicationBase.java | 31 +- .../aad/msal4j/IMDSManagedIdentitySource.java | 10 +- .../msal4j/IManagedIdentityApplication.java | 2 +- .../msal4j/ManagedIdentityApplication.java | 37 +- .../aad/msal4j/ManagedIdentityClient.java | 10 +- .../aad/msal4j/ManagedIdentityId.java | 16 +- .../aad/msal4j/ManagedIdentityIdType.java | 6 +- .../aad/msal4j/ManagedIdentityRequest.java | 2 - .../aad/msal4j/ManagedIdentityResponse.java | 10 +- .../aad/msal4j/ManagedIdentitySourceType.java | 26 +- .../com/microsoft/aad/msal4j/MsalRequest.java | 10 +- .../aad/msal4j/RefreshTokenRequest.java | 4 +- .../aad/msal4j/RemoveAccountRunnable.java | 2 +- .../microsoft/aad/msal4j/RequestContext.java | 12 +- .../microsoft/aad/msal4j/SilentRequest.java | 4 +- .../aad/msal4j/TokenRequestExecutor.java | 10 +- .../aad/msal4j/AadInstanceDiscoveryTest.java | 10 +- .../msal4j/EnvironmentVariablesHelper.java | 10 +- .../ManagedIdentityTestDataProvider.java | 46 +-- .../aad/msal4j/ManagedIdentityTests.java | 14 +- .../aad/msal4j/ServerTelemetryTests.java | 2 +- 34 files changed, 573 insertions(+), 471 deletions(-) create mode 100644 msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractApplicationBase.java create mode 100644 msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IApplicationBase.java diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java index 2cbd728a..a2a7c6c8 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java @@ -64,29 +64,35 @@ static InstanceDiscoveryMetadataEntry getMetadataEntry(URL authorityUrl, ServiceBundle serviceBundle) { String host = authorityUrl.getHost(); - if (shouldUseRegionalEndpoint(msalRequest)) { + if (msalRequest.application() instanceof AbstractClientApplicationBase && shouldUseRegionalEndpoint(msalRequest)) { //Server side telemetry requires the result from region discovery when any part of the region API is used String detectedRegion = discoverRegion(msalRequest, serviceBundle); - if (msalRequest.application().azureRegion() != null) { - host = getRegionalizedHost(authorityUrl.getHost(), msalRequest.application().azureRegion()); + if (((AbstractClientApplicationBase) msalRequest.application()).azureRegion() != null) { + host = getRegionalizedHost(authorityUrl.getHost(), + ((AbstractClientApplicationBase) msalRequest.application()).azureRegion()); } //If region autodetection is enabled and a specific region not already set, // set the application's region to the discovered region so that future requests can skip the IMDS endpoint call - if (null == msalRequest.application().azureRegion() && msalRequest.application().autoDetectRegion() + if (null == ((AbstractClientApplicationBase) msalRequest.application()).azureRegion() + && ((AbstractClientApplicationBase) msalRequest.application()).autoDetectRegion() && null != detectedRegion) { - msalRequest.application().azureRegion = detectedRegion; + ((AbstractClientApplicationBase) msalRequest.application()).azureRegion = detectedRegion; } - cacheRegionInstanceMetadata(authorityUrl.getHost(), msalRequest.application().azureRegion()); + cacheRegionInstanceMetadata(authorityUrl.getHost(), ((AbstractClientApplicationBase) msalRequest.application()).azureRegion()); serviceBundle.getServerSideTelemetry().getCurrentRequest().regionOutcome( - determineRegionOutcome(detectedRegion, msalRequest.application().azureRegion(), msalRequest.application().autoDetectRegion())); + determineRegionOutcome(detectedRegion, + ((AbstractClientApplicationBase) msalRequest.application()).azureRegion(), + ((AbstractClientApplicationBase) msalRequest.application()).autoDetectRegion())); } InstanceDiscoveryMetadataEntry result = cache.get(host); if (result == null) { - if(msalRequest.application().instanceDiscovery() && !instanceDiscoveryFailed){ + if(msalRequest.application() instanceof AbstractClientApplicationBase && + ((AbstractClientApplicationBase) msalRequest.application()).instanceDiscovery() + && !instanceDiscoveryFailed){ doInstanceDiscoveryAndCache(authorityUrl, validateAuthority, msalRequest, serviceBundle); } else { // instanceDiscovery flag is set to False. Do not perform instanceDiscovery. @@ -145,7 +151,8 @@ static void cacheInstanceDiscoveryMetadata(String host, private static boolean shouldUseRegionalEndpoint(MsalRequest msalRequest){ - if (msalRequest.application().azureRegion() != null || msalRequest.application().autoDetectRegion()){ + if (((AbstractClientApplicationBase) msalRequest.application()).azureRegion() != null + || ((AbstractClientApplicationBase) msalRequest.application()).autoDetectRegion()){ //This class type check is a quick and dirty fix to accommodate changes to the internal workings of the region API // //ESTS-R only supports a small, but growing, number of scenarios, and the original design failed silently whenever diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractApplicationBase.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractApplicationBase.java new file mode 100644 index 00000000..1d905626 --- /dev/null +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractApplicationBase.java @@ -0,0 +1,352 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.aad.msal4j; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.experimental.Accessors; +import org.slf4j.Logger; + +import javax.net.ssl.SSLSocketFactory; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; + +import static com.microsoft.aad.msal4j.ParameterValidationUtils.validateNotBlank; +import static com.microsoft.aad.msal4j.ParameterValidationUtils.validateNotNull; + +/** + * Abstract class containing common methods and properties for {@link PublicClientApplication}, + * {@link ConfidentialClientApplication}, and {@link ManagedIdentityApplication} + */ +public abstract class AbstractApplicationBase implements IApplicationBase { + + protected Logger log; + protected Authority authenticationAuthority; + + @Accessors(fluent = true) + @Getter + private String correlationId; + + @Accessors(fluent = true) + @Getter + private boolean logPii; + + @Accessors(fluent = true) + @Getter + private Proxy proxy; + + @Accessors(fluent = true) + @Getter + private SSLSocketFactory sslSocketFactory; + + @Accessors(fluent = true) + @Getter + private IHttpClient httpClient; + + @Accessors(fluent = true) + @Getter + private Integer connectTimeoutForDefaultHttpClient; + + @Accessors(fluent = true) + @Getter + private Integer readTimeoutForDefaultHttpClient; + + //The following fields are set in only some applications and/or set internally by the library. To avoid excessive + // type casting throughout the library they are defined here as package-private, but will not be part of this class's Builder + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + private boolean validateAuthority; + + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + private String clientId; + + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + private String authority; + + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + private ServiceBundle serviceBundle; + + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + private Consumer>> telemetryConsumer; + + @Accessors(fluent = true) + @Getter(AccessLevel.PACKAGE) + protected TokenCache tokenCache; + + CompletableFuture executeRequest( + MsalRequest msalRequest) { + + AuthenticationResultSupplier supplier = getAuthenticationResultSupplier(msalRequest); + + ExecutorService executorService = serviceBundle.getExecutorService(); + return executorService != null ? + CompletableFuture.supplyAsync(supplier, executorService) : + CompletableFuture.supplyAsync(supplier); + + } + + AuthenticationResult acquireTokenCommon(MsalRequest msalRequest, Authority requestAuthority) + throws Exception { + + HttpHeaders headers = msalRequest.headers(); + + if (logPii) { + log.debug(LogHelper.createMessage( + String.format("Using Client Http Headers: %s", headers), + headers.getHeaderCorrelationIdValue())); + } + + TokenRequestExecutor requestExecutor = new TokenRequestExecutor( + requestAuthority, + msalRequest, + serviceBundle); + + AuthenticationResult result = requestExecutor.executeTokenRequest(); + + if (authenticationAuthority.authorityType.equals(AuthorityType.AAD)) { + InstanceDiscoveryMetadataEntry instanceDiscoveryMetadata = + AadInstanceDiscoveryProvider.getMetadataEntry( + requestAuthority.canonicalAuthorityUrl(), + validateAuthority, + msalRequest, + serviceBundle); + + tokenCache.saveTokens(requestExecutor, result, instanceDiscoveryMetadata.preferredCache); + } else { + tokenCache.saveTokens(requestExecutor, result, authenticationAuthority.host); + } + + return result; + } + + private AuthenticationResultSupplier getAuthenticationResultSupplier(MsalRequest msalRequest) { + + AuthenticationResultSupplier supplier; + if (msalRequest instanceof DeviceCodeFlowRequest) { + supplier = new AcquireTokenByDeviceCodeFlowSupplier( + (PublicClientApplication) this, + (DeviceCodeFlowRequest) msalRequest); + } else if (msalRequest instanceof SilentRequest) { + supplier = new AcquireTokenSilentSupplier(this, (SilentRequest) msalRequest); + } else if (msalRequest instanceof InteractiveRequest) { + supplier = new AcquireTokenByInteractiveFlowSupplier( + (PublicClientApplication) this, + (InteractiveRequest) msalRequest); + } else if (msalRequest instanceof ClientCredentialRequest) { + supplier = new AcquireTokenByClientCredentialSupplier( + (ConfidentialClientApplication) this, + (ClientCredentialRequest) msalRequest); + } else if (msalRequest instanceof OnBehalfOfRequest) { + supplier = new AcquireTokenByOnBehalfOfSupplier( + (ConfidentialClientApplication) this, + (OnBehalfOfRequest) msalRequest); + } else if (msalRequest instanceof ManagedIdentityRequest) { + supplier = new AcquireTokenByManagedIdentitySupplier( + (ManagedIdentityApplication) this, + (ManagedIdentityRequest) msalRequest); + } else { + supplier = new AcquireTokenByAuthorizationGrantSupplier( + this, + msalRequest, null); + } + return supplier; + } + + public abstract static class Builder> { + // Optional parameters - initialized to default values + private String correlationId; + private boolean logPii = false; + private ExecutorService executorService; + private Proxy proxy; + private SSLSocketFactory sslSocketFactory; + private IHttpClient httpClient; + private Consumer>> telemetryConsumer; + private Boolean onlySendFailureTelemetry = false; + private Integer connectTimeoutForDefaultHttpClient; + private Integer readTimeoutForDefaultHttpClient; + private String clientId; + private Authority authenticationAuthority = createDefaultAADAuthority(); + + public Builder() { + } + + public Builder(String clientId) { + validateNotBlank("clientId", clientId); + this.clientId = clientId; + } + + abstract T self(); + + /** + * Set optional correlation id to be used by the API. + * If not provided, the API generates a random UUID. + * + * @param val a string value of correlation id + * @return instance of the Builder on which method was called + */ + public T correlationId(String val) { + validateNotBlank("correlationId", val); + + correlationId = val; + return self(); + } + + /** + * Set logPii - boolean value, which determines + * whether Pii (personally identifiable information) will be logged in. + * The default value is false. + * + * @param val a boolean value for logPii + * @return instance of the Builder on which method was called + */ + public T logPii(boolean val) { + logPii = val; + return self(); + } + + /** + * Sets ExecutorService to be used to execute the requests. + * Developer is responsible for maintaining the lifecycle of the ExecutorService. + * + * @param val an instance of ExecutorService + * @return instance of the Builder on which method was called + */ + public T executorService(ExecutorService val) { + validateNotNull("executorService", val); + + executorService = val; + return self(); + } + + /** + * Sets Proxy configuration to be used by the client application (MSAL4J by default uses + * {@link javax.net.ssl.HttpsURLConnection}) for all network communication. + * If no proxy value is passed in, system defined properties are used. If HTTP client is set on + * the client application (via ClientApplication.builder().httpClient()), + * proxy configuration should be done on the HTTP client object being passed in, + * and not through this method. + * + * @param val an instance of Proxy + * @return instance of the Builder on which method was called + */ + public T proxy(Proxy val) { + validateNotNull("proxy", val); + + proxy = val; + return self(); + } + + /** + * Sets HTTP client to be used by the client application for all HTTP requests. Allows for fine + * grained configuration of HTTP client. + * + * @param val Implementation of {@link IHttpClient} + * @return instance of the Builder on which method was called + */ + public T httpClient(IHttpClient val) { + validateNotNull("httpClient", val); + + httpClient = val; + return self(); + } + + /** + * Sets SSLSocketFactory to be used by the client application for all network communication. + * If HTTP client is set on the client application (via ClientApplication.builder().httpClient()), + * any configuration of SSL should be done on the HTTP client and not through this method. + * + * @param val an instance of SSLSocketFactory + * @return instance of the Builder on which method was called + */ + public T sslSocketFactory(SSLSocketFactory val) { + validateNotNull("sslSocketFactory", val); + + sslSocketFactory = val; + return self(); + } + + /** + * Sets the connect timeout value used in HttpsURLConnection connections made by {@link DefaultHttpClient}, + * and is not needed if using a custom HTTP client + * + * @param val timeout value in milliseconds + * @return instance of the Builder on which method was called + */ + public T connectTimeoutForDefaultHttpClient(Integer val) { + validateNotNull("connectTimeoutForDefaultHttpClient", val); + + connectTimeoutForDefaultHttpClient = val; + return self(); + } + + /** + * Sets the read timeout value used in HttpsURLConnection connections made by {@link DefaultHttpClient}, + * and is not needed if using a custom HTTP client + * + * @param val timeout value in milliseconds + * @return instance of the Builder on which method was called + */ + public T readTimeoutForDefaultHttpClient(Integer val) { + validateNotNull("readTimeoutForDefaultHttpClient", val); + + readTimeoutForDefaultHttpClient = val; + return self(); + } + + T telemetryConsumer(Consumer>> val) { + validateNotNull("telemetryConsumer", val); + + telemetryConsumer = val; + return self(); + } + + T onlySendFailureTelemetry(Boolean val) { + + onlySendFailureTelemetry = val; + return self(); + } + + private static Authority createDefaultAADAuthority() { + Authority authority; + try { + authority = new AADAuthority(new URL(DEFAULT_AUTHORITY)); + } catch (Exception e) { + throw new MsalClientException(e); + } + return authority; + } + + + abstract AbstractApplicationBase build(); + } + + AbstractApplicationBase(Builder builder) { + correlationId = builder.correlationId; + logPii = builder.logPii; + telemetryConsumer = builder.telemetryConsumer; + proxy = builder.proxy; + sslSocketFactory = builder.sslSocketFactory; + connectTimeoutForDefaultHttpClient = builder.connectTimeoutForDefaultHttpClient; + readTimeoutForDefaultHttpClient = builder.readTimeoutForDefaultHttpClient; + serviceBundle = new ServiceBundle( + builder.executorService, + builder.httpClient == null ? + new DefaultHttpClient(builder.proxy, builder.sslSocketFactory, builder.connectTimeoutForDefaultHttpClient, builder.readTimeoutForDefaultHttpClient) : + builder.httpClient, + new TelemetryManager(telemetryConsumer, builder.onlySendFailureTelemetry)); + authenticationAuthority = builder.authenticationAuthority; + clientId = builder.clientId; + } +} diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java index a3f03b0e..9a3e19d8 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java @@ -28,11 +28,7 @@ * Abstract class containing common methods and properties to both {@link PublicClientApplication} * and {@link ConfidentialClientApplication}. */ -public abstract class AbstractClientApplicationBase implements IClientApplicationBase { - - protected Logger log; - protected Authority authenticationAuthority; - private ServiceBundle serviceBundle; +public abstract class AbstractClientApplicationBase extends AbstractApplicationBase implements IClientApplicationBase { @Accessors(fluent = true) @Getter @@ -46,38 +42,6 @@ public abstract class AbstractClientApplicationBase implements IClientApplicatio @Getter private boolean validateAuthority; - @Accessors(fluent = true) - @Getter - private String correlationId; - - @Accessors(fluent = true) - @Getter - private boolean logPii; - - @Accessors(fluent = true) - @Getter(AccessLevel.PACKAGE) - private Consumer>> telemetryConsumer; - - @Accessors(fluent = true) - @Getter - private Proxy proxy; - - @Accessors(fluent = true) - @Getter - private SSLSocketFactory sslSocketFactory; - - @Accessors(fluent = true) - @Getter - private Integer connectTimeoutForDefaultHttpClient; - - @Accessors(fluent = true) - @Getter - private Integer readTimeoutForDefaultHttpClient; - - @Accessors(fluent = true) - @Getter - protected TokenCache tokenCache; - @Accessors(fluent = true) @Getter private String applicationName; @@ -108,6 +72,11 @@ public abstract class AbstractClientApplicationBase implements IClientApplicatio @Getter private boolean instanceDiscovery; + @Override + public TokenCache tokenCache() { + return super.tokenCache; + } + @Override public CompletableFuture acquireToken(AuthorizationCodeParameters parameters) { @@ -174,7 +143,6 @@ public CompletableFuture acquireTokenSilently(SilentParam return executeRequest(silentRequest); } - @Override public CompletableFuture> getAccounts() { RequestContext context = new RequestContext(this, PublicApi.GET_ACCOUNTS, null); @@ -184,12 +152,11 @@ public CompletableFuture> getAccounts() { AccountsSupplier supplier = new AccountsSupplier(this, msalRequest); - return serviceBundle.getExecutorService() != null ? - CompletableFuture.supplyAsync(supplier, serviceBundle.getExecutorService()) : + return super.serviceBundle().getExecutorService() != null ? + CompletableFuture.supplyAsync(supplier, super.serviceBundle().getExecutorService()) : CompletableFuture.supplyAsync(supplier); } - @Override public CompletableFuture removeAccount(IAccount account) { RequestContext context = new RequestContext(this, PublicApi.REMOVE_ACCOUNTS, null); MsalRequest msalRequest = new MsalRequest(this, null, context) { @@ -197,8 +164,8 @@ public CompletableFuture removeAccount(IAccount account) { RemoveAccountRunnable runnable = new RemoveAccountRunnable(msalRequest, account); - return serviceBundle.getExecutorService() != null ? - CompletableFuture.runAsync(runnable, serviceBundle.getExecutorService()) : + return super.serviceBundle().getExecutorService() != null ? + CompletableFuture.runAsync(runnable, super.serviceBundle().getExecutorService()) : CompletableFuture.runAsync(runnable); } @@ -225,90 +192,7 @@ public URL getAuthorizationRequestUrl(AuthorizationRequestUrlParameters paramete parameters.requestParameters()); } - CompletableFuture executeRequest( - MsalRequest msalRequest) { - - AuthenticationResultSupplier supplier = getAuthenticationResultSupplier(msalRequest); - - ExecutorService executorService = serviceBundle.getExecutorService(); - return executorService != null ? - CompletableFuture.supplyAsync(supplier, executorService) : - CompletableFuture.supplyAsync(supplier); - - } - - AuthenticationResult acquireTokenCommon(MsalRequest msalRequest, Authority requestAuthority) - throws Exception { - - HttpHeaders headers = msalRequest.headers(); - - if (logPii) { - log.debug(LogHelper.createMessage( - String.format("Using Client Http Headers: %s", headers), - headers.getHeaderCorrelationIdValue())); - } - - TokenRequestExecutor requestExecutor = new TokenRequestExecutor( - requestAuthority, - msalRequest, - serviceBundle); - - AuthenticationResult result = requestExecutor.executeTokenRequest(); - - if (authenticationAuthority.authorityType.equals(AuthorityType.AAD)) { - InstanceDiscoveryMetadataEntry instanceDiscoveryMetadata = - AadInstanceDiscoveryProvider.getMetadataEntry( - requestAuthority.canonicalAuthorityUrl(), - validateAuthority, - msalRequest, - serviceBundle); - - tokenCache.saveTokens(requestExecutor, result, instanceDiscoveryMetadata.preferredCache); - } else { - tokenCache.saveTokens(requestExecutor, result, authenticationAuthority.host); - } - - return result; - } - - private AuthenticationResultSupplier getAuthenticationResultSupplier(MsalRequest msalRequest) { - - AuthenticationResultSupplier supplier; - if (msalRequest instanceof DeviceCodeFlowRequest) { - supplier = new AcquireTokenByDeviceCodeFlowSupplier( - (PublicClientApplication) this, - (DeviceCodeFlowRequest) msalRequest); - } else if (msalRequest instanceof SilentRequest) { - supplier = new AcquireTokenSilentSupplier(this, (SilentRequest) msalRequest); - } else if (msalRequest instanceof InteractiveRequest) { - supplier = new AcquireTokenByInteractiveFlowSupplier( - (PublicClientApplication) this, - (InteractiveRequest) msalRequest); - } else if (msalRequest instanceof ClientCredentialRequest) { - supplier = new AcquireTokenByClientCredentialSupplier( - (ConfidentialClientApplication) this, - (ClientCredentialRequest) msalRequest); - } else if (msalRequest instanceof OnBehalfOfRequest) { - supplier = new AcquireTokenByOnBehalfOfSupplier( - (ConfidentialClientApplication) this, - (OnBehalfOfRequest) msalRequest); - } else if (msalRequest instanceof ManagedIdentityRequest) { - supplier = new AcquireTokenByManagedIdentitySupplier( - (ManagedIdentityApplication) this, - (ManagedIdentityRequest) msalRequest); - } else { - supplier = new AcquireTokenByAuthorizationGrantSupplier( - this, - msalRequest, null); - } - return supplier; - } - - ServiceBundle getServiceBundle() { - return serviceBundle; - } - - public abstract static class Builder> { + public abstract static class Builder> extends AbstractApplicationBase.Builder { // Required parameters private String clientId; @@ -316,14 +200,6 @@ public abstract static class Builder> { private String authority = DEFAULT_AUTHORITY; private Authority authenticationAuthority = createDefaultAADAuthority(); private boolean validateAuthority = true; - private String correlationId; - private boolean logPii = false; - private ExecutorService executorService; - private Proxy proxy; - private SSLSocketFactory sslSocketFactory; - private IHttpClient httpClient; - private Consumer>> telemetryConsumer; - private Boolean onlySendFailureTelemetry = false; private String applicationName; private String applicationVersion; private ITokenCacheAccessAspect tokenCacheAccessAspect; @@ -331,8 +207,6 @@ public abstract static class Builder> { private String clientCapabilities; private boolean autoDetectRegion; private String azureRegion; - private Integer connectTimeoutForDefaultHttpClient; - private Integer readTimeoutForDefaultHttpClient; protected boolean isInstanceDiscoveryEnabled = true; /** @@ -425,135 +299,6 @@ public T validateAuthority(boolean val) { return self(); } - /** - * Set optional correlation id to be used by the API. - * If not provided, the API generates a random UUID. - * - * @param val a string value of correlation id - * @return instance of the Builder on which method was called - */ - public T correlationId(String val) { - validateNotBlank("correlationId", val); - - correlationId = val; - return self(); - } - - /** - * Set logPii - boolean value, which determines - * whether Pii (personally identifiable information) will be logged in. - * The default value is false. - * - * @param val a boolean value for logPii - * @return instance of the Builder on which method was called - */ - public T logPii(boolean val) { - logPii = val; - return self(); - } - - /** - * Sets ExecutorService to be used to execute the requests. - * Developer is responsible for maintaining the lifecycle of the ExecutorService. - * - * @param val an instance of ExecutorService - * @return instance of the Builder on which method was called - */ - public T executorService(ExecutorService val) { - validateNotNull("executorService", val); - - executorService = val; - return self(); - } - - /** - * Sets Proxy configuration to be used by the client application (MSAL4J by default uses - * {@link javax.net.ssl.HttpsURLConnection}) for all network communication. - * If no proxy value is passed in, system defined properties are used. If HTTP client is set on - * the client application (via ClientApplication.builder().httpClient()), - * proxy configuration should be done on the HTTP client object being passed in, - * and not through this method. - * - * @param val an instance of Proxy - * @return instance of the Builder on which method was called - */ - public T proxy(Proxy val) { - validateNotNull("proxy", val); - - proxy = val; - return self(); - } - - /** - * Sets HTTP client to be used by the client application for all HTTP requests. Allows for fine - * grained configuration of HTTP client. - * - * @param val Implementation of {@link IHttpClient} - * @return instance of the Builder on which method was called - */ - public T httpClient(IHttpClient val) { - validateNotNull("httpClient", val); - - httpClient = val; - return self(); - } - - /** - * Sets SSLSocketFactory to be used by the client application for all network communication. - * If HTTP client is set on the client application (via ClientApplication.builder().httpClient()), - * any configuration of SSL should be done on the HTTP client and not through this method. - * - * @param val an instance of SSLSocketFactory - * @return instance of the Builder on which method was called - */ - public T sslSocketFactory(SSLSocketFactory val) { - validateNotNull("sslSocketFactory", val); - - sslSocketFactory = val; - return self(); - } - - /** - * Sets the connect timeout value used in HttpsURLConnection connections made by {@link DefaultHttpClient}, - * and is not needed if using a custom HTTP client - * - * @param val timeout value in milliseconds - * @return instance of the Builder on which method was called - */ - public T connectTimeoutForDefaultHttpClient(Integer val) { - validateNotNull("connectTimeoutForDefaultHttpClient", val); - - connectTimeoutForDefaultHttpClient = val; - return self(); - } - - /** - * Sets the read timeout value used in HttpsURLConnection connections made by {@link DefaultHttpClient}, - * and is not needed if using a custom HTTP client - * - * @param val timeout value in milliseconds - * @return instance of the Builder on which method was called - */ - public T readTimeoutForDefaultHttpClient(Integer val) { - validateNotNull("readTimeoutForDefaultHttpClient", val); - - readTimeoutForDefaultHttpClient = val; - return self(); - } - - T telemetryConsumer(Consumer>> val) { - validateNotNull("telemetryConsumer", val); - - telemetryConsumer = val; - return self(); - } - - T onlySendFailureTelemetry(Boolean val) { - - onlySendFailureTelemetry = val; - return self(); - } - /** * Sets application name for telemetry purposes * @@ -685,26 +430,14 @@ public T instanceDiscovery(boolean val) { } AbstractClientApplicationBase(Builder builder) { + super(builder); clientId = builder.clientId; authority = builder.authority; validateAuthority = builder.validateAuthority; - correlationId = builder.correlationId; - logPii = builder.logPii; applicationName = builder.applicationName; applicationVersion = builder.applicationVersion; - telemetryConsumer = builder.telemetryConsumer; - proxy = builder.proxy; - sslSocketFactory = builder.sslSocketFactory; - connectTimeoutForDefaultHttpClient = builder.connectTimeoutForDefaultHttpClient; - readTimeoutForDefaultHttpClient = builder.readTimeoutForDefaultHttpClient; - serviceBundle = new ServiceBundle( - builder.executorService, - builder.httpClient == null ? - new DefaultHttpClient(builder.proxy, builder.sslSocketFactory, builder.connectTimeoutForDefaultHttpClient, builder.readTimeoutForDefaultHttpClient) : - builder.httpClient, - new TelemetryManager(telemetryConsumer, builder.onlySendFailureTelemetry)); authenticationAuthority = builder.authenticationAuthority; - tokenCache = new TokenCache(builder.tokenCacheAccessAspect); + super.tokenCache = new TokenCache(builder.tokenCacheAccessAspect); aadAadInstanceDiscoveryResponse = builder.aadInstanceDiscoveryResponse; clientCapabilities = builder.clientCapabilities; autoDetectRegion = builder.autoDetectRegion; diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAppProviderSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAppProviderSupplier.java index 4966f0de..1c0173f8 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAppProviderSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAppProviderSupplier.java @@ -58,7 +58,7 @@ AuthenticationResult execute() throws Exception { TokenRequestExecutor tokenRequestExecutor = new TokenRequestExecutor( clientCredentialRequest.application().authenticationAuthority, msalRequest, - clientApplication.getServiceBundle() + clientApplication.serviceBundle() ); clientApplication.tokenCache.saveTokens(tokenRequestExecutor, authenticationResult, clientCredentialRequest.application().authenticationAuthority.host); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAuthorizationGrantSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAuthorizationGrantSupplier.java index b38a8202..4931c2ce 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAuthorizationGrantSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByAuthorizationGrantSupplier.java @@ -18,7 +18,7 @@ class AcquireTokenByAuthorizationGrantSupplier extends AuthenticationResultSuppl private Authority requestAuthority; private MsalRequest msalRequest; - AcquireTokenByAuthorizationGrantSupplier(AbstractClientApplicationBase clientApplication, + AcquireTokenByAuthorizationGrantSupplier(AbstractApplicationBase clientApplication, MsalRequest msalRequest, Authority authority) { super(clientApplication, msalRequest); @@ -92,7 +92,7 @@ private OAuthAuthorizationGrant processPasswordGrant( this.clientApplication.authenticationAuthority.getUserRealmEndpoint(grant.getUsername()), msalRequest.headers().getReadonlyHeaderMap(), msalRequest.requestContext(), - this.clientApplication.getServiceBundle()); + this.clientApplication.serviceBundle()); if (userDiscoveryResponse.isAccountFederated()) { WSTrustResponse response = WSTrustRequest.execute( @@ -101,7 +101,7 @@ private OAuthAuthorizationGrant processPasswordGrant( grant.getPassword().getValue(), userDiscoveryResponse.cloudAudienceUrn(), msalRequest.requestContext(), - this.clientApplication.getServiceBundle(), + this.clientApplication.serviceBundle(), this.clientApplication.logPii()); AuthorizationGrant updatedGrant = getSAMLAuthorizationGrant(response); @@ -135,7 +135,7 @@ private AuthorizationGrant getAuthorizationGrantIntegrated(String userName) thro userRealmEndpoint, msalRequest.headers().getReadonlyHeaderMap(), msalRequest.requestContext(), - this.clientApplication.getServiceBundle()); + this.clientApplication.serviceBundle()); if (userRealmResponse.isAccountFederated() && "WSTrust".equalsIgnoreCase(userRealmResponse.federationProtocol())) { @@ -149,7 +149,7 @@ private AuthorizationGrant getAuthorizationGrantIntegrated(String userName) thro mexURL, cloudAudienceUrn, msalRequest.requestContext(), - this.clientApplication.getServiceBundle(), + this.clientApplication.serviceBundle(), this.clientApplication.logPii()); updatedGrant = getSAMLAuthorizationGrant(wsTrustResponse); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByClientCredentialSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByClientCredentialSupplier.java index c41d86d8..41a756cf 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByClientCredentialSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByClientCredentialSupplier.java @@ -71,7 +71,7 @@ private AuthenticationResult acquireTokenByClientCredential() throws Exception { ); AcquireTokenByAppProviderSupplier supplier = - new AcquireTokenByAppProviderSupplier(this.clientApplication, + new AcquireTokenByAppProviderSupplier((AbstractClientApplicationBase) this.clientApplication, clientCredentialRequest, appTokenProviderParameters); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java index 92c33ced..351ae24a 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java @@ -33,7 +33,7 @@ private DeviceCode getDeviceCode(Authority requestAuthority) { requestAuthority.deviceCodeEndpoint(), clientApplication.clientId(), deviceCodeFlowRequest.headers().getReadonlyHeaderMap(), - this.clientApplication.getServiceBundle()); + this.clientApplication.serviceBundle()); deviceCodeFlowRequest.parameters().deviceCodeConsumer().accept(deviceCode); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByManagedIdentitySupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByManagedIdentitySupplier.java index d1a58777..c7c4d4e9 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByManagedIdentitySupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByManagedIdentitySupplier.java @@ -32,7 +32,7 @@ AuthenticationResult execute() throws Exception { TokenRequestExecutor tokenRequestExecutor = new TokenRequestExecutor( clientApplication.authenticationAuthority, msalRequest, - clientApplication.getServiceBundle() + clientApplication.serviceBundle() ); if (!managedIdentityParameters.forceRefresh) { diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java index 558fa407..8f1d150b 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java @@ -14,7 +14,7 @@ class AcquireTokenSilentSupplier extends AuthenticationResultSupplier { private SilentRequest silentRequest; - AcquireTokenSilentSupplier(AbstractClientApplicationBase clientApplication, SilentRequest silentRequest) { + AcquireTokenSilentSupplier(AbstractApplicationBase clientApplication, SilentRequest silentRequest) { super(clientApplication, silentRequest); this.silentRequest = silentRequest; @@ -47,7 +47,7 @@ AuthenticationResult execute() throws Exception { } if (!StringHelper.isBlank(res.accessToken())) { - clientApplication.getServiceBundle().getServerSideTelemetry().incrementSilentSuccessfulCount(); + clientApplication.serviceBundle().getServerSideTelemetry().incrementSilentSuccessfulCount(); } //Determine if the current token needs to be refreshed according to the refresh_in value @@ -60,16 +60,16 @@ AuthenticationResult execute() throws Exception { //As of version 3 of the telemetry schema, there is a field for collecting data about why a token was refreshed, // so here we set the telemetry value based on the cause of the refresh if (silentRequest.parameters().forceRefresh()) { - clientApplication.getServiceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( + clientApplication.serviceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( CacheTelemetry.REFRESH_FORCE_REFRESH.telemetryValue); } else if (afterRefreshOn) { - clientApplication.getServiceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( + clientApplication.serviceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( CacheTelemetry.REFRESH_REFRESH_IN.telemetryValue); } else if (res.expiresOn() < currTimeStampSec) { - clientApplication.getServiceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( + clientApplication.serviceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( CacheTelemetry.REFRESH_ACCESS_TOKEN_EXPIRED.telemetryValue); } else if (StringHelper.isBlank(res.accessToken())) { - clientApplication.getServiceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( + clientApplication.serviceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( CacheTelemetry.REFRESH_NO_ACCESS_TOKEN.telemetryValue); } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AppServiceManagedIdentitySource.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AppServiceManagedIdentitySource.java index bc5216eb..6081c16e 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AppServiceManagedIdentitySource.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AppServiceManagedIdentitySource.java @@ -49,7 +49,7 @@ public void createManagedIdentityRequest(String resource) { private AppServiceManagedIdentitySource(MsalRequest msalRequest, ServiceBundle serviceBundle, URI msiEndpoint, String secret) { - super(msalRequest, serviceBundle, ManagedIdentitySourceType.AppService); + super(msalRequest, serviceBundle, ManagedIdentitySourceType.APP_SERVICE); this.MSI_ENDPOINT = msiEndpoint; this.SECRET = secret; } @@ -83,7 +83,7 @@ private static URI validateAndGetUri(String msiEndpoint, String secret) { throw new MsalManagedIdentityException(MsalError.INVALID_MANAGED_IDENTITY_ENDPOINT, String.format( MsalErrorMessage.MANAGED_IDENTITY_ENDPOINT_INVALID_URI_ERROR, "IDENTITY_ENDPOINT", msiEndpoint, "App Service"), - ManagedIdentitySourceType.AppService); + ManagedIdentitySourceType.APP_SERVICE); } LOG.info("[Managed Identity] Environment variables validation passed for app service managed identity. Endpoint URI: {endpointUri}. Creating App Service managed identity."); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java index c7770620..890e9b40 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java @@ -17,10 +17,10 @@ abstract class AuthenticationResultSupplier implements Supplier { - AbstractClientApplicationBase clientApplication; + AbstractApplicationBase clientApplication; MsalRequest msalRequest; - AuthenticationResultSupplier(AbstractClientApplicationBase clientApplication, MsalRequest msalRequest) { + AuthenticationResultSupplier(AbstractApplicationBase clientApplication, MsalRequest msalRequest) { this.clientApplication = clientApplication; this.msalRequest = msalRequest; } @@ -40,7 +40,7 @@ Authority getAuthorityWithPrefNetworkHost(String authority) throws MalformedURLE authorityUrl, clientApplication.validateAuthority(), msalRequest, - clientApplication.getServiceBundle()); + clientApplication.serviceBundle()); URL updatedAuthorityUrl = new URL( authorityUrl.getProtocol(), @@ -60,7 +60,7 @@ public IAuthenticationResult get() { ApiEvent apiEvent = initializeApiEvent(msalRequest); try (TelemetryHelper telemetryHelper = - clientApplication.getServiceBundle().getTelemetryManager().createTelemetryHelper( + clientApplication.serviceBundle().getTelemetryManager().createTelemetryHelper( msalRequest.requestContext().telemetryRequestId(), msalRequest.application().clientId(), apiEvent, @@ -90,7 +90,7 @@ public IAuthenticationResult get() { } } - clientApplication.getServiceBundle().getServerSideTelemetry().addFailedRequestTelemetry( + clientApplication.serviceBundle().getServerSideTelemetry().addFailedRequestTelemetry( String.valueOf(msalRequest.requestContext().publicApi().getApiId()), msalRequest.requestContext().correlationId(), error); @@ -158,7 +158,7 @@ private void logException(Exception ex) { private ApiEvent initializeApiEvent(MsalRequest msalRequest) { ApiEvent apiEvent = new ApiEvent(clientApplication.logPii()); msalRequest.requestContext().telemetryRequestId( - clientApplication.getServiceBundle().getTelemetryManager().generateRequestId()); + clientApplication.serviceBundle().getTelemetryManager().generateRequestId()); apiEvent.setApiId(msalRequest.requestContext().publicApi().getApiId()); apiEvent.setCorrelationId(msalRequest.requestContext().correlationId()); apiEvent.setRequestId(msalRequest.requestContext().telemetryRequestId()); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/CloudShellManagedIdentitySource.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/CloudShellManagedIdentitySource.java index 6182801f..40ac11e7 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/CloudShellManagedIdentitySource.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/CloudShellManagedIdentitySource.java @@ -32,15 +32,15 @@ public void createManagedIdentityRequest(String resource) { private CloudShellManagedIdentitySource(MsalRequest msalRequest, ServiceBundle serviceBundle, URI msiEndpoint) { - super(msalRequest, serviceBundle, ManagedIdentitySourceType.CloudShell); + super(msalRequest, serviceBundle, ManagedIdentitySourceType.CLOUD_SHELL); this.MSI_ENDPOINT = msiEndpoint; ManagedIdentityIdType idType = ((ManagedIdentityApplication) msalRequest.application()).getManagedIdentityId().getIdType(); - if (idType != ManagedIdentityIdType.SystemAssigned) { + if (idType != ManagedIdentityIdType.SYSTEM_ASSIGNED) { throw new MsalManagedIdentityException(MsalError.USER_ASSIGNED_MANAGED_IDENTITY_NOT_SUPPORTED, String.format(MsalErrorMessage.MANAGED_IDENTITY_USER_ASSIGNED_NOT_SUPPORTED, "cloud shell"), - ManagedIdentitySourceType.CloudShell); + ManagedIdentitySourceType.CLOUD_SHELL); } } @@ -74,7 +74,7 @@ private static URI validateAndGetUri(String msiEndpoint) { throw new MsalManagedIdentityException(MsalError.INVALID_MANAGED_IDENTITY_ENDPOINT, String.format( MsalErrorMessage.MANAGED_IDENTITY_ENDPOINT_INVALID_URI_ERROR, "MSI_ENDPOINT", msiEndpoint, "Cloud Shell"), - ManagedIdentitySourceType.CloudShell); + ManagedIdentitySourceType.CLOUD_SHELL); } LOG.info("[Managed Identity] Environment variables validation passed for cloud shell managed identity. Endpoint URI: " + endpointUri + ". Creating cloud shell managed identity."); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IApplicationBase.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IApplicationBase.java new file mode 100644 index 00000000..83735eb5 --- /dev/null +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IApplicationBase.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.microsoft.aad.msal4j; + +import javax.net.ssl.SSLSocketFactory; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.util.concurrent.CompletableFuture; + +/** + * Interface representing an application for which tokens can be acquired. + */ +interface IApplicationBase { + + String DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/"; + + /** + * @return a boolean value which determines whether Pii (personally identifiable information) will be logged in + */ + boolean logPii(); + + /** + * @return Correlation ID which is used for diagnostics purposes, is attached to token service requests + * Default value is random UUID + */ + String correlationId(); + + /** + * Sets HTTP client to be used by the client application for all HTTP requests. Allows for fine-grained + * configuration of HTTP client. + + * @return instance of IHttpClient used by the application + */ + IHttpClient httpClient(); + + /** + * @return proxy used by the application for all network communication. + */ + Proxy proxy(); + + /** + * @return SSLSocketFactory used by the application for all network communication. + */ + SSLSocketFactory sslSocketFactory(); +} diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java index 65412b39..45f5daef 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java @@ -13,9 +13,7 @@ /** * Interface representing an application for which tokens can be acquired. */ -interface IClientApplicationBase { - - String DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/"; +interface IClientApplicationBase extends IApplicationBase { /** * @return Client ID (Application ID) of the application as registered in the application registration portal @@ -34,33 +32,6 @@ interface IClientApplicationBase { */ boolean validateAuthority(); - /** - * @return Correlation Id which is used for diagnostics purposes, is attached to token service requests - * Default value is random UUID - */ - String correlationId(); - - /** - * @return a boolean value which determines whether Pii (personally identifiable information) will be logged in - */ - boolean logPii(); - - /** - * @return proxy used by the application for all network communication. - */ - Proxy proxy(); - - /** - * @return SSLSocketFactory used by the application for all network communication. - */ - SSLSocketFactory sslSocketFactory(); - - /** - * @return Cache holding access tokens, refresh tokens, id tokens. It is maintained and used silently - * if needed when calling {@link IClientApplicationBase#acquireTokenSilently(SilentParameters)} - */ - ITokenCache tokenCache(); - // /** // * @return Telemetry consumer that will receive telemetry events emitted by the library. // */ diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IMDSManagedIdentitySource.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IMDSManagedIdentitySource.java index 779ed9aa..5bc87133 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IMDSManagedIdentitySource.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IMDSManagedIdentitySource.java @@ -22,7 +22,7 @@ class IMDSManagedIdentitySource extends AbstractManagedIdentitySource{ try { DEFAULT_IMDS_ENDPOINT = new URI("http://169.254.169.254/metadata/identity/oauth2/token"); } catch (URISyntaxException e) { - throw new MsalManagedIdentityException(MsalError.INVALID_MANAGED_IDENTITY_ENDPOINT, ManagedIdentitySourceType.Imds); + throw new MsalManagedIdentityException(MsalError.INVALID_MANAGED_IDENTITY_ENDPOINT, ManagedIdentitySourceType.IMDS); } } @@ -33,7 +33,7 @@ class IMDSManagedIdentitySource extends AbstractManagedIdentitySource{ public IMDSManagedIdentitySource(MsalRequest msalRequest, ServiceBundle serviceBundle) { - super(msalRequest, serviceBundle, ManagedIdentitySourceType.Imds); + super(msalRequest, serviceBundle, ManagedIdentitySourceType.IMDS); ManagedIdentityParameters parameters = (ManagedIdentityParameters) msalRequest.requestContext().apiParameters(); IEnvironmentVariables environmentVariables = ((ManagedIdentityParameters) msalRequest.requestContext().apiParameters()).environmentVariables == null ? new EnvironmentVariables() : @@ -55,8 +55,8 @@ public IMDSManagedIdentitySource(MsalRequest msalRequest, String.format(MsalErrorMessage.MANAGED_IDENTITY_ENDPOINT_INVALID_URI_ERROR, Constants.AZURE_POD_IDENTITY_AUTHORITY_HOST, builder.toString(), - ManagedIdentitySourceType.Imds), - ManagedIdentitySourceType.Imds); + ManagedIdentitySourceType.IMDS), + ManagedIdentitySourceType.IMDS); } } else @@ -122,7 +122,7 @@ public ManagedIdentityResponse handleResponse( LOG.error(String.format("Error message: %s Http status code: %s"), message, response.statusCode()); throw new MsalManagedIdentityException(MsalError.MANAGED_IDENTITY_REQUEST_FAILED, message, - ManagedIdentitySourceType.Imds); + ManagedIdentitySourceType.IMDS); } // Default behavior to handle successful scenario and general errors. diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IManagedIdentityApplication.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IManagedIdentityApplication.java index e73e1ac1..9aa56551 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IManagedIdentityApplication.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/IManagedIdentityApplication.java @@ -12,7 +12,7 @@ * without using credentials. * For details see https://aka.ms/msal4jclientapplications */ -public interface IManagedIdentityApplication extends IClientApplicationBase { +public interface IManagedIdentityApplication extends IApplicationBase { /** * Acquires tokens from the configured managed identity on an azure resource. diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityApplication.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityApplication.java index 2be676f7..10d432ff 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityApplication.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityApplication.java @@ -3,7 +3,6 @@ package com.microsoft.aad.msal4j; -import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; import lombok.Getter; import org.slf4j.LoggerFactory; @@ -15,7 +14,7 @@ *

* Conditionally thread-safe */ -public class ManagedIdentityApplication extends AbstractClientApplicationBase implements IManagedIdentityApplication { +public class ManagedIdentityApplication extends AbstractApplicationBase implements IManagedIdentityApplication { @Getter private final ManagedIdentityId managedIdentityId; @@ -24,17 +23,7 @@ private ManagedIdentityApplication(Builder builder) { super(builder); this.managedIdentityId = builder.managedIdentityId; log = LoggerFactory.getLogger(ManagedIdentityApplication.class); - } - - /** - * Creates instance of Builder of ManagedIdentityApplication - * - * @param managedIdentityId ManagedIdentityId to specify if System Assigned or User Assigned - * and provide id if it is user assigned. - * @return instance of Builder of ManagedIdentityApplication - */ - public static Builder builder(ManagedIdentityId managedIdentityId) { - return new Builder(managedIdentityId); + super.tokenCache = new TokenCache(); } @Override @@ -42,7 +31,7 @@ public CompletableFuture acquireTokenForManagedIdentity(M throws Exception { RequestContext requestContext = new RequestContext( this, - managedIdentityId.getIdType() == ManagedIdentityIdType.SystemAssigned ? + managedIdentityId.getIdType() == ManagedIdentityIdType.SYSTEM_ASSIGNED ? PublicApi.ACQUIRE_TOKEN_BY_SYSTEM_ASSIGNED_MANAGED_IDENTITY : PublicApi.ACQUIRE_TOKEN_BY_USER_ASSIGNED_MANAGED_IDENTITY, managedIdentityParameters); @@ -52,23 +41,27 @@ public CompletableFuture acquireTokenForManagedIdentity(M return this.executeRequest(managedIdentityRequest); } - @Override - protected ClientAuthentication clientAuthentication() { - return null; + /** + * Creates instance of Builder of ManagedIdentityApplication + * + * @param managedIdentityId ManagedIdentityId to specify if System Assigned or User Assigned + * and provide id if it is user assigned. + * @return instance of Builder of ManagedIdentityApplication + */ + public static Builder builder(ManagedIdentityId managedIdentityId) { + return new Builder(managedIdentityId); } - public static class Builder extends AbstractClientApplicationBase.Builder { - private String resource; + public static class Builder extends AbstractApplicationBase.Builder { + private String resource; private ManagedIdentityId managedIdentityId; private Builder(ManagedIdentityId managedIdentityId) { - super(managedIdentityId.getIdType() == ManagedIdentityIdType.SystemAssigned ? + super(managedIdentityId.getIdType() == ManagedIdentityIdType.SYSTEM_ASSIGNED ? "system_assigned_managed_identity" : managedIdentityId.getUserAssignedId()); - this.managedIdentityId = managedIdentityId; - this.isInstanceDiscoveryEnabled = false; } public Builder resource(String resource) { diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityClient.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityClient.java index 04981239..66986f98 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityClient.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityClient.java @@ -10,23 +10,23 @@ class ManagedIdentityClient { private AbstractManagedIdentitySource managedIdentitySource; - public ManagedIdentityClient(MsalRequest msalRequest, ServiceBundle serviceBundle) throws Exception { + ManagedIdentityClient(MsalRequest msalRequest, ServiceBundle serviceBundle) throws Exception { managedIdentitySource = createManagedIdentitySource(msalRequest, serviceBundle); ManagedIdentityApplication managedIdentityApplication = (ManagedIdentityApplication) msalRequest.application(); ManagedIdentityIdType identityIdType = managedIdentityApplication.getManagedIdentityId().getIdType(); - if (!identityIdType.equals(ManagedIdentityIdType.SystemAssigned)) { + if (!identityIdType.equals(ManagedIdentityIdType.SYSTEM_ASSIGNED)) { managedIdentitySource.setUserAssignedManagedIdentity(true); String userAssignedId = managedIdentityApplication.getManagedIdentityId().getUserAssignedId(); - if (identityIdType.equals(ManagedIdentityIdType.ClientId)) { + if (identityIdType.equals(ManagedIdentityIdType.CLIENT_ID)) { managedIdentitySource.setManagedIdentityUserAssignedClientId(userAssignedId); - } else if (identityIdType.equals(ManagedIdentityIdType.ResourceId)) { + } else if (identityIdType.equals(ManagedIdentityIdType.RESOURCE_ID)) { managedIdentitySource.setManagedIdentityUserAssignedResourceId(userAssignedId); } } } - public ManagedIdentityResponse getManagedIdentityResponse(ManagedIdentityParameters parameters) { + ManagedIdentityResponse getManagedIdentityResponse(ManagedIdentityParameters parameters) { return managedIdentitySource.getManagedIdentityResponse(parameters); } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityId.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityId.java index 64b2b8df..20c28728 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityId.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityId.java @@ -5,11 +5,10 @@ import lombok.Getter; +@Getter public class ManagedIdentityId { - @Getter private String userAssignedId; - @Getter private ManagedIdentityIdType idType; private ManagedIdentityId(ManagedIdentityIdType idType) @@ -24,31 +23,34 @@ private ManagedIdentityId(ManagedIdentityIdType idType, String id) { /** * Create an instance of a system assigned managed identity. + * * @return Instance of ManagedIdentityId. */ public static ManagedIdentityId systemAssigned() { - return new ManagedIdentityId(ManagedIdentityIdType.SystemAssigned); + return new ManagedIdentityId(ManagedIdentityIdType.SYSTEM_ASSIGNED); } /** * Create an instance of ManagedIdentityId for a user assigned managed identity from a client id. + * * @param clientId Client id of the user assigned managed identity assigned to azure resource. * @return Instance of ManagedIdentityId - * @exception NullPointerException + * @exception NullPointerException Indicates the clientId param is null or blank */ public static ManagedIdentityId userAssignedClientId(String clientId) { if (StringHelper.isNullOrBlank(clientId)) { throw new NullPointerException(clientId); } - return new ManagedIdentityId(ManagedIdentityIdType.ClientId, clientId); + return new ManagedIdentityId(ManagedIdentityIdType.CLIENT_ID, clientId); } /** * Create an instance of ManagedIdentityId for a user assigned managed identity from a resource id. + * * @param resourceId Resource ID of the user assigned managed identity assigned to azure resource. * @return Instance of ManagedIdentityId - * @exception NullPointerException + * @exception NullPointerException Indicates the resourceId param is null or blank */ public static ManagedIdentityId userAssignedResourceId(String resourceId) { @@ -57,6 +59,6 @@ public static ManagedIdentityId userAssignedResourceId(String resourceId) throw new NullPointerException(resourceId); } - return new ManagedIdentityId(ManagedIdentityIdType.ResourceId, resourceId); + return new ManagedIdentityId(ManagedIdentityIdType.RESOURCE_ID, resourceId); } } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityIdType.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityIdType.java index 9c5f1ebb..8f7fbe44 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityIdType.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityIdType.java @@ -5,7 +5,7 @@ enum ManagedIdentityIdType { - SystemAssigned, - ClientId, - ResourceId + SYSTEM_ASSIGNED, + CLIENT_ID, + RESOURCE_ID } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityRequest.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityRequest.java index 7d20efb0..bf77b65c 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityRequest.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityRequest.java @@ -3,14 +3,12 @@ package com.microsoft.aad.msal4j; -import com.nimbusds.oauth2.sdk.util.URIUtils; import com.nimbusds.oauth2.sdk.util.URLUtils; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityResponse.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityResponse.java index afe3f48e..171c47f5 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityResponse.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentityResponse.java @@ -9,15 +9,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.Locale; - @Getter -public class ManagedIdentityResponse { +class ManagedIdentityResponse { + + private static final Logger LOG = LoggerFactory.getLogger(ManagedIdentityResponse.class); - private final static Logger LOG = LoggerFactory.getLogger(ManagedIdentityResponse.class); @JsonProperty(value = "token_type") String tokenType; diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentitySourceType.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentitySourceType.java index bfd8b884..66bddf6a 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentitySourceType.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/ManagedIdentitySourceType.java @@ -3,17 +3,17 @@ package com.microsoft.aad.msal4j; -public enum ManagedIdentitySourceType { - /// Default. - None, - /// The source to acquire token for managed identity is IMDS. - Imds, - /// The source to acquire token for managed identity is App Service. - AppService, - /// The source to acquire token for managed identity is Azure Arc. - AzureArc, - /// The source to acquire token for managed identity is Cloud Shell. - CloudShell, - /// The source to acquire token for managed identity is Service Fabric. - ServiceFabric +enum ManagedIdentitySourceType { + // Default. + NONE, + // The source to acquire token for managed identity is IMDS. + IMDS, + // The source to acquire token for managed identity is App Service. + APP_SERVICE, + // The source to acquire token for managed identity is Azure Arc. + AZURE_ARC, + // The source to acquire token for managed identity is Cloud Shell. + CLOUD_SHELL, + // The source to acquire token for managed identity is Service Fabric. + SERVICE_FABRIC } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java index 51e620d3..a6b680ce 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java @@ -15,28 +15,28 @@ abstract class MsalRequest { AbstractMsalAuthorizationGrant msalAuthorizationGrant; - private final AbstractClientApplicationBase application; + private final AbstractApplicationBase application; private final RequestContext requestContext; @Getter(value = AccessLevel.PACKAGE, lazy = true) private final HttpHeaders headers = new HttpHeaders(requestContext); - MsalRequest(AbstractClientApplicationBase clientApplicationBase, AbstractMsalAuthorizationGrant abstractMsalAuthorizationGrant, RequestContext requestContext) { + MsalRequest(AbstractApplicationBase clientApplicationBase, AbstractMsalAuthorizationGrant abstractMsalAuthorizationGrant, RequestContext requestContext) { this.application = clientApplicationBase; this.msalAuthorizationGrant = abstractMsalAuthorizationGrant; this.requestContext = requestContext; CurrentRequest currentRequest = new CurrentRequest(requestContext.publicApi()); - application.getServiceBundle().getServerSideTelemetry().setCurrentRequest(currentRequest); + application.serviceBundle().getServerSideTelemetry().setCurrentRequest(currentRequest); } - MsalRequest(AbstractClientApplicationBase clientApplicationBase, RequestContext requestContext) { + MsalRequest(AbstractApplicationBase clientApplicationBase, RequestContext requestContext) { this.application = clientApplicationBase; this.requestContext = requestContext; CurrentRequest currentRequest = new CurrentRequest(requestContext.publicApi()); - application.getServiceBundle().getServerSideTelemetry().setCurrentRequest(currentRequest); + application.serviceBundle().getServerSideTelemetry().setCurrentRequest(currentRequest); } MsalRequest() { diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java index 3e354900..f9983c60 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java @@ -17,14 +17,14 @@ class RefreshTokenRequest extends MsalRequest { private RefreshTokenParameters parameters; RefreshTokenRequest(RefreshTokenParameters parameters, - AbstractClientApplicationBase application, + AbstractApplicationBase application, RequestContext requestContext) { super(application, createAuthenticationGrant(parameters), requestContext); this.parameters = parameters; } RefreshTokenRequest(RefreshTokenParameters parameters, - AbstractClientApplicationBase application, + AbstractApplicationBase application, RequestContext requestContext, SilentRequest silentRequest) { this(parameters, application, requestContext); diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RemoveAccountRunnable.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RemoveAccountRunnable.java index 5586de51..d6cc0a48 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RemoveAccountRunnable.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RemoveAccountRunnable.java @@ -9,7 +9,7 @@ class RemoveAccountRunnable implements Runnable { private RequestContext requestContext; - private AbstractClientApplicationBase clientApplication; + private AbstractApplicationBase clientApplication; IAccount account; RemoveAccountRunnable(MsalRequest msalRequest, IAccount account) { diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RequestContext.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RequestContext.java index 582076a2..409f3ab8 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RequestContext.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/RequestContext.java @@ -23,10 +23,10 @@ class RequestContext { private String applicationVersion; private String authority; private IAcquireTokenParameters apiParameters; - private IClientApplicationBase clientApplication; + private IApplicationBase clientApplication; private UserIdentifier userIdentifier; - public RequestContext(AbstractClientApplicationBase clientApplication, + public RequestContext(AbstractApplicationBase clientApplication, PublicApi publicApi, IAcquireTokenParameters apiParameters) { this.clientApplication = clientApplication; @@ -38,14 +38,16 @@ public RequestContext(AbstractClientApplicationBase clientApplication, generateNewCorrelationId() : clientApplication.correlationId(); - this.applicationVersion = clientApplication.applicationVersion(); - this.applicationName = clientApplication.applicationName(); + if (clientApplication instanceof AbstractClientApplicationBase) { + this.applicationVersion = ((AbstractClientApplicationBase) clientApplication).applicationVersion(); + this.applicationName = ((AbstractClientApplicationBase) clientApplication).applicationName(); + } this.publicApi = publicApi; this.authority = clientApplication.authority(); this.apiParameters = apiParameters; } - public RequestContext(AbstractClientApplicationBase clientApplication, + public RequestContext(AbstractApplicationBase clientApplication, PublicApi publicApi, IAcquireTokenParameters apiParameters, UserIdentifier userIdentifier) { diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/SilentRequest.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/SilentRequest.java index 59ba47fb..82053ae7 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/SilentRequest.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/SilentRequest.java @@ -18,7 +18,7 @@ class SilentRequest extends MsalRequest { private Authority requestAuthority; SilentRequest(SilentParameters parameters, - AbstractClientApplicationBase application, + AbstractApplicationBase application, RequestContext requestContext, IUserAssertion assertion) throws MalformedURLException { @@ -31,7 +31,7 @@ class SilentRequest extends MsalRequest { Authority.createAuthority(new URL(Authority.enforceTrailingSlash(parameters.authorityUrl()))); if (parameters.forceRefresh()) { - application.getServiceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( + application.serviceBundle().getServerSideTelemetry().getCurrentRequest().cacheInfo( CacheTelemetry.REFRESH_FORCE_REFRESH.telemetryValue); } } diff --git a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java index 50805df2..7dadba69 100644 --- a/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java +++ b/msal4j-sdk/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java @@ -55,8 +55,9 @@ OAuthHttpRequest createOauthHttpRequest() throws SerializeException, MalformedUR oauthHttpRequest.setContentType(HTTPContentType.ApplicationURLEncoded.contentType); final Map> params = new HashMap<>(msalRequest.msalAuthorizationGrant().toParameters()); - if (msalRequest.application().clientCapabilities() != null) { - params.put("claims", Collections.singletonList(msalRequest.application().clientCapabilities())); + if (msalRequest.application() instanceof AbstractClientApplicationBase + && ((AbstractClientApplicationBase) msalRequest.application()).clientCapabilities() != null) { + params.put("claims", Collections.singletonList(((AbstractClientApplicationBase) msalRequest.application()).clientCapabilities())); } if (msalRequest.msalAuthorizationGrant.getClaims() != null) { @@ -78,7 +79,8 @@ OAuthHttpRequest createOauthHttpRequest() throws SerializeException, MalformedUR oauthHttpRequest.setQuery(URLUtils.serializeParameters(params)); - if (msalRequest.application().clientAuthentication() != null) { + if (msalRequest.application() instanceof AbstractClientApplicationBase + && ((AbstractClientApplicationBase) msalRequest.application()).clientAuthentication() != null) { Map> queryParameters = oauthHttpRequest.getQueryParameters(); String clientID = msalRequest.application().clientId(); @@ -92,7 +94,7 @@ OAuthHttpRequest createOauthHttpRequest() throws SerializeException, MalformedUR .createClientAuthFromClientAssertion((ClientAssertion) ((ClientCredentialRequest) msalRequest).parameters.clientCredential()) .applyTo(oauthHttpRequest); } else { - msalRequest.application().clientAuthentication().applyTo(oauthHttpRequest); + ((AbstractClientApplicationBase) msalRequest.application()).clientAuthentication().applyTo(oauthHttpRequest); } } return oauthHttpRequest; diff --git a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java index 8e5aa477..8f73e4a2 100644 --- a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java +++ b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java @@ -63,13 +63,13 @@ void aadInstanceDiscoveryTest_NotSetByDeveloper() throws Exception { mockedInstanceDiscoveryProvider.when(() -> AadInstanceDiscoveryProvider.sendInstanceDiscoveryRequest(authority, msalRequest, - app.getServiceBundle())).thenReturn(expectedResponse); + app.serviceBundle())).thenReturn(expectedResponse); InstanceDiscoveryMetadataEntry entry = AadInstanceDiscoveryProvider.getMetadataEntry( authority, false, msalRequest, - app.getServiceBundle()); + app.serviceBundle()); assertValidResponse(entry); } @@ -93,7 +93,7 @@ void aadInstanceDiscoveryTest_responseSetByDeveloper_validResponse() throws Exce authority, false, msalRequest, - app.getServiceBundle()); + app.serviceBundle()); assertValidResponse(entry); } @@ -128,13 +128,13 @@ void aadInstanceDiscoveryTest_AutoDetectRegion_NoRegionDetected() throws Excepti try (MockedStatic mocked = mockStatic(AadInstanceDiscoveryProvider.class, CALLS_REAL_METHODS)) { mocked.when(() -> AadInstanceDiscoveryProvider.discoverRegion(msalRequest, - app.getServiceBundle())).thenReturn(null); + app.serviceBundle())).thenReturn(null); InstanceDiscoveryMetadataEntry entry = AadInstanceDiscoveryProvider.getMetadataEntry( authority, false, msalRequest, - app.getServiceBundle()); + app.serviceBundle()); assertValidResponse(entry); } diff --git a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/EnvironmentVariablesHelper.java b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/EnvironmentVariablesHelper.java index ba931a92..6249cafa 100644 --- a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/EnvironmentVariablesHelper.java +++ b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/EnvironmentVariablesHelper.java @@ -13,26 +13,26 @@ public class EnvironmentVariablesHelper implements IEnvironmentVariables { mockedEnvironmentVariables = new HashMap<>(); switch (source) { - case AppService: + case APP_SERVICE: mockedEnvironmentVariables.put(Constants.IDENTITY_ENDPOINT, endpoint); mockedEnvironmentVariables.put(Constants.IDENTITY_HEADER, "secret"); break; - case Imds: + case IMDS: mockedEnvironmentVariables.put(Constants.IMDS_ENDPOINT, endpoint); break; - case ServiceFabric: + case SERVICE_FABRIC: mockedEnvironmentVariables.put(Constants.IDENTITY_ENDPOINT, endpoint); mockedEnvironmentVariables.put(Constants.IDENTITY_HEADER, "secret"); mockedEnvironmentVariables.put(Constants.IDENTITY_SERVER_THUMBPRINT, "thumbprint"); break; - case CloudShell: + case CLOUD_SHELL: mockedEnvironmentVariables.put(Constants.MSI_ENDPOINT, endpoint); break; - case AzureArc: + case AZURE_ARC: mockedEnvironmentVariables.put(Constants.IDENTITY_ENDPOINT, endpoint); mockedEnvironmentVariables.put(Constants.IMDS_ENDPOINT, endpoint); break; diff --git a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTestDataProvider.java b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTestDataProvider.java index a564bd5d..4cc23404 100644 --- a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTestDataProvider.java +++ b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTestDataProvider.java @@ -7,68 +7,68 @@ import java.util.stream.Stream; -public class ManagedIdentityTestDataProvider { +class ManagedIdentityTestDataProvider { private static final String CLIENT_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"; private static final String RESOURCE_ID = "/subscriptions/ffa4aaa2-4444-4444-5555-e3ccedd3d046/resourcegroups/UAMI_group/providers/Microsoft.ManagedIdentityClient/userAssignedIdentities/UAMI"; public static Stream createData() { return Stream.of( - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, ManagedIdentityTests.resource), - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, ManagedIdentityTests.resourceDefaultSuffix), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, ManagedIdentityTests.resource), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, ManagedIdentityTests.resourceDefaultSuffix), - Arguments.of(ManagedIdentitySourceType.Imds, ManagedIdentityTests.IMDS_ENDPOINT, + Arguments.of(ManagedIdentitySourceType.IMDS, ManagedIdentityTests.IMDS_ENDPOINT, ManagedIdentityTests.resource), - Arguments.of(ManagedIdentitySourceType.Imds, ManagedIdentityTests.IMDS_ENDPOINT, + Arguments.of(ManagedIdentitySourceType.IMDS, ManagedIdentityTests.IMDS_ENDPOINT, ManagedIdentityTests.resourceDefaultSuffix), - Arguments.of(ManagedIdentitySourceType.Imds, null, + Arguments.of(ManagedIdentitySourceType.IMDS, null, ManagedIdentityTests.resource)); } public static Stream createDataUserAssigned() { return Stream.of( - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, ManagedIdentityId.userAssignedClientId(CLIENT_ID)), - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, ManagedIdentityId.userAssignedResourceId(RESOURCE_ID)), - Arguments.of(ManagedIdentitySourceType.Imds, null, + Arguments.of(ManagedIdentitySourceType.IMDS, null, ManagedIdentityId.userAssignedClientId(CLIENT_ID)), - Arguments.of(ManagedIdentitySourceType.Imds, null, + Arguments.of(ManagedIdentitySourceType.IMDS, null, ManagedIdentityId.userAssignedResourceId(RESOURCE_ID))); } public static Stream createDataUserAssignedNotSupported() { return Stream.of( - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, ManagedIdentityId.userAssignedClientId(CLIENT_ID)), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, ManagedIdentityId.userAssignedResourceId(RESOURCE_ID))); } public static Stream createDataWrongScope() { return Stream.of( - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, "user.read"), - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint, + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint, "https://management.core.windows.net//user_impersonation"), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, "user.read"), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint, + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint, "https://management.core.windows.net//user_impersonation"), - Arguments.of(ManagedIdentitySourceType.Imds, ManagedIdentityTests.IMDS_ENDPOINT, + Arguments.of(ManagedIdentitySourceType.IMDS, ManagedIdentityTests.IMDS_ENDPOINT, "user.read"), - Arguments.of(ManagedIdentitySourceType.Imds, ManagedIdentityTests.IMDS_ENDPOINT, + Arguments.of(ManagedIdentitySourceType.IMDS, ManagedIdentityTests.IMDS_ENDPOINT, "https://management.core.windows.net//user_impersonation")); } public static Stream createDataError() { return Stream.of( - Arguments.of(ManagedIdentitySourceType.AppService, ManagedIdentityTests.appServiceEndpoint), - Arguments.of(ManagedIdentitySourceType.CloudShell, ManagedIdentityTests.cloudShellEndpoint), - Arguments.of(ManagedIdentitySourceType.Imds, ManagedIdentityTests.IMDS_ENDPOINT)); + Arguments.of(ManagedIdentitySourceType.APP_SERVICE, ManagedIdentityTests.appServiceEndpoint), + Arguments.of(ManagedIdentitySourceType.CLOUD_SHELL, ManagedIdentityTests.cloudShellEndpoint), + Arguments.of(ManagedIdentitySourceType.IMDS, ManagedIdentityTests.IMDS_ENDPOINT)); } } diff --git a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTests.java b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTests.java index c2ae9ec4..8a468b93 100644 --- a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTests.java +++ b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ManagedIdentityTests.java @@ -23,7 +23,7 @@ @ExtendWith(MockitoExtension.class) @TestInstance(TestInstance.Lifecycle.PER_METHOD) -public class ManagedIdentityTests { +class ManagedIdentityTests { static final String resource = "https://management.azure.com"; final static String resourceDefaultSuffix = "https://management.azure.com/.default"; @@ -55,7 +55,7 @@ private HttpRequest expectedRequest(ManagedIdentitySourceType source, String res Map> bodyParameters = new HashMap<>(); switch (source) { - case AppService: { + case APP_SERVICE: { endpoint = appServiceEndpoint; queryParameters.put("api-version", Collections.singletonList("2019-08-01")); @@ -64,7 +64,7 @@ private HttpRequest expectedRequest(ManagedIdentitySourceType source, String res headers.put("X-IDENTITY-HEADER", "secret"); break; } - case CloudShell: { + case CLOUD_SHELL: { endpoint = cloudShellEndpoint; headers.put("ContentType", "application/x-www-form-urlencoded"); @@ -73,7 +73,7 @@ private HttpRequest expectedRequest(ManagedIdentitySourceType source, String res bodyParameters.put("resource", Collections.singletonList(resource)); return new HttpRequest(HttpMethod.POST, computeUri(endpoint, queryParameters), headers, URLUtils.serializeParameters(bodyParameters)); } - case Imds: { + case IMDS: { endpoint = IMDS_ENDPOINT; queryParameters.put("api-version", Collections.singletonList("2018-02-01")); queryParameters.put("resource", Collections.singletonList(resource)); @@ -83,10 +83,10 @@ private HttpRequest expectedRequest(ManagedIdentitySourceType source, String res } switch (id.getIdType()) { - case ClientId: + case CLIENT_ID: queryParameters.put("client_id", Collections.singletonList(id.getUserAssignedId())); break; - case ResourceId: + case RESOURCE_ID: queryParameters.put("mi_res_id", Collections.singletonList(id.getUserAssignedId())); break; } @@ -185,7 +185,7 @@ void managedIdentityTest_UserAssigned_NotSupported(ManagedIdentitySourceType sou assertInstanceOf(MsalManagedIdentityException.class, e.getCause()); MsalManagedIdentityException msalMsiException = (MsalManagedIdentityException) e.getCause(); - assertEquals(ManagedIdentitySourceType.CloudShell, msalMsiException.managedIdentitySourceType); + assertEquals(ManagedIdentitySourceType.CLOUD_SHELL, msalMsiException.managedIdentitySourceType); assertEquals(MsalError.USER_ASSIGNED_MANAGED_IDENTITY_NOT_SUPPORTED, msalMsiException.errorCode()); return; } diff --git a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java index ae9c2e65..bf3d06fb 100644 --- a/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java +++ b/msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java @@ -197,7 +197,7 @@ public void serverTelemetryHeaders_testRegionTelemetry() throws Exception { fail("Expected MsalException was not thrown"); } catch (Exception ex) { - headers = pca.getServiceBundle().getServerSideTelemetry().getServerTelemetryHeaderMap(); + headers = pca.serviceBundle().getServerSideTelemetry().getServerTelemetryHeaderMap(); assertEquals(headers.get(CURRENT_REQUEST_HEADER_NAME), "5|300,,,0,0|"); }