From 10c2271c3746b1643891abe12fe514ad06bfa15f Mon Sep 17 00:00:00 2001 From: Avery-Dunn Date: Mon, 12 Jul 2021 14:55:31 -0700 Subject: [PATCH] Minor code formatting applied to most files --- .../AcquireTokenInteractiveIT.java | 42 +++++----- .../AcquireTokenSilentIT.java | 21 +++-- .../ApacheHttpClientAdapter.java | 18 ++--- .../AuthorizationCodeIT.java | 72 +++++++++--------- .../AzureEnvironmentIT.java | 10 +-- .../CachePersistenceIT.java | 14 ++-- .../CertificateHelper.java | 5 +- .../ClientCredentialsIT.java | 10 +-- .../ConfidentialClientApplicationUnitT.java | 2 +- .../java/com.microsoft.aad.msal4j/Config.java | 6 +- .../DeviceCodeIT.java | 24 +++--- .../EnvironmentsProvider.java | 6 +- .../HttpClientIT.java | 2 +- .../OkHttpClientAdapter.java | 22 +++--- .../OnBehalfOfIT.java | 6 +- .../RefreshTokenIT.java | 14 ++-- .../SeleniumTest.java | 13 ++-- .../TokenCacheIT.java | 26 +++---- .../UsernamePasswordIT.java | 38 +++++----- .../infrastructure/SeleniumExtensions.java | 29 +++---- .../infrastructure/UserInformationFields.java | 17 ++--- .../java/labapi/AppCredentialProvider.java | 16 ++-- .../java/labapi/B2CProvider.java | 2 +- .../java/labapi/HttpClientHelper.java | 10 +-- .../java/labapi/KeyVaultSecretsProvider.java | 31 ++++---- .../java/labapi/LabConstants.java | 2 +- .../java/labapi/LabService.java | 13 ++-- .../java/labapi/LabUserProvider.java | 34 ++++----- src/integrationtest/java/labapi/User.java | 3 +- .../microsoft/aad/msal4j/AADAuthority.java | 2 +- .../microsoft/aad/msal4j/ADFSAuthority.java | 2 +- .../msal4j/AadInstanceDiscoveryProvider.java | 16 ++-- .../msal4j/AbstractClientApplicationBase.java | 4 +- .../AbstractMsalAuthorizationGrant.java | 2 +- .../com/microsoft/aad/msal4j/Account.java | 1 + .../aad/msal4j/AccountCacheEntity.java | 4 +- .../AcquireTokenByDeviceCodeFlowSupplier.java | 4 +- .../msal4j/AcquireTokenSilentSupplier.java | 3 +- .../com/microsoft/aad/msal4j/ApiEvent.java | 30 ++++---- .../aad/msal4j/AppMetadataCacheEntity.java | 2 +- .../msal4j/AuthenticationResultSupplier.java | 73 +++++++++--------- .../com/microsoft/aad/msal4j/Authority.java | 2 +- .../msal4j/AuthorizationCodeParameters.java | 3 +- .../aad/msal4j/AuthorizationCodeRequest.java | 8 +- .../AuthorizationRequestUrlParameters.java | 76 +++++++++---------- .../msal4j/AuthorizationResponseHandler.java | 34 ++++----- .../aad/msal4j/AuthorizationResult.java | 18 ++--- .../aad/msal4j/AzureCloudEndpoint.java | 2 +- .../microsoft/aad/msal4j/B2CAuthority.java | 10 +-- .../microsoft/aad/msal4j/CacheTelemetry.java | 2 +- .../microsoft/aad/msal4j/ClaimsRequest.java | 10 +-- .../aad/msal4j/ClientAuthenticationPost.java | 4 +- .../aad/msal4j/ClientCertificate.java | 9 +-- .../aad/msal4j/ClientCredentialFactory.java | 17 +++-- .../msal4j/ClientCredentialParameters.java | 1 + .../aad/msal4j/ClientCredentialRequest.java | 6 +- .../com/microsoft/aad/msal4j/ClientInfo.java | 6 +- .../microsoft/aad/msal4j/ClientSecret.java | 5 +- .../microsoft/aad/msal4j/CurrentRequest.java | 2 +- .../microsoft/aad/msal4j/DefaultEvent.java | 14 ++-- .../aad/msal4j/DefaultHttpClient.java | 17 ++--- .../com/microsoft/aad/msal4j/DeviceCode.java | 6 +- .../msal4j/DeviceCodeAuthorizationGrant.java | 4 +- .../aad/msal4j/DeviceCodeFlowParameters.java | 7 +- .../aad/msal4j/DeviceCodeFlowRequest.java | 4 +- .../java/com/microsoft/aad/msal4j/Event.java | 22 +++--- .../com/microsoft/aad/msal4j/EventKey.java | 11 ++- .../com/microsoft/aad/msal4j/HttpEvent.java | 42 +++++----- .../com/microsoft/aad/msal4j/HttpHelper.java | 5 +- .../microsoft/aad/msal4j/HttpListener.java | 6 +- .../com/microsoft/aad/msal4j/HttpRequest.java | 20 ++--- .../microsoft/aad/msal4j/HttpResponse.java | 10 +-- .../com/microsoft/aad/msal4j/HttpUtils.java | 6 +- .../com/microsoft/aad/msal4j/IAccount.java | 1 - .../aad/msal4j/IAcquireTokenParameters.java | 2 + .../aad/msal4j/IClientApplicationBase.java | 4 +- .../aad/msal4j/IClientAssertion.java | 4 +- .../aad/msal4j/IClientCertificate.java | 8 +- .../aad/msal4j/IClientCredential.java | 2 +- .../microsoft/aad/msal4j/IClientSecret.java | 4 +- .../IConfidentialClientApplication.java | 4 +- .../com/microsoft/aad/msal4j/IHttpClient.java | 9 ++- .../microsoft/aad/msal4j/IHttpResponse.java | 1 - .../aad/msal4j/IPublicClientApplication.java | 12 ++- .../com/microsoft/aad/msal4j/ITelemetry.java | 2 + .../microsoft/aad/msal4j/ITenantProfile.java | 1 - .../com/microsoft/aad/msal4j/ITokenCache.java | 2 +- .../aad/msal4j/ITokenCacheAccessAspect.java | 2 +- .../aad/msal4j/ITokenCacheAccessContext.java | 2 +- .../com/microsoft/aad/msal4j/IdToken.java | 2 +- .../aad/msal4j/IdTokenCacheEntity.java | 2 +- ...gratedWindowsAuthenticationParameters.java | 9 ++- ...ntegratedWindowsAuthenticationRequest.java | 8 +- .../aad/msal4j/InteractionRequiredCache.java | 13 ++-- .../InteractionRequiredExceptionReason.java | 12 +-- .../aad/msal4j/InteractiveRequest.java | 12 +-- .../msal4j/InteractiveRequestParameters.java | 2 +- .../com/microsoft/aad/msal4j/JsonHelper.java | 5 +- .../com/microsoft/aad/msal4j/JwtHelper.java | 13 ++-- .../com/microsoft/aad/msal4j/MexParser.java | 68 +++++++---------- .../aad/msal4j/MsalClientException.java | 8 +- .../microsoft/aad/msal4j/MsalException.java | 2 + .../MsalInteractionRequiredException.java | 7 +- .../com/microsoft/aad/msal4j/MsalRequest.java | 2 +- .../aad/msal4j/MsalServiceException.java | 9 ++- .../aad/msal4j/MsalThrottlingException.java | 1 + .../aad/msal4j/NamespaceContextImpl.java | 1 + .../aad/msal4j/OAuthAuthorizationGrant.java | 8 +- .../aad/msal4j/OAuthHttpRequest.java | 10 +-- .../aad/msal4j/OnBehalfOfParameters.java | 5 +- .../aad/msal4j/OpenBrowserAction.java | 1 + .../java/com/microsoft/aad/msal4j/Prompt.java | 18 ++--- .../com/microsoft/aad/msal4j/PublicApi.java | 4 +- .../aad/msal4j/RefreshTokenCacheEntity.java | 9 +-- .../aad/msal4j/RefreshTokenParameters.java | 11 +-- .../aad/msal4j/RefreshTokenRequest.java | 2 +- .../microsoft/aad/msal4j/RegionTelemetry.java | 4 +- .../microsoft/aad/msal4j/RequestedClaim.java | 1 + .../msal4j/RequestedClaimAdditionalInfo.java | 1 + .../microsoft/aad/msal4j/ResponseMode.java | 4 +- .../aad/msal4j/SAML11BearerGrant.java | 2 +- .../msal4j/SafeDocumentBuilderFactory.java | 6 +- .../microsoft/aad/msal4j/ServiceBundle.java | 8 +- .../aad/msal4j/SilentParameters.java | 9 +-- .../aad/msal4j/SystemBrowserOptions.java | 6 +- .../microsoft/aad/msal4j/TelemetryHelper.java | 10 +-- .../aad/msal4j/TelemetryManager.java | 54 ++++++------- .../microsoft/aad/msal4j/TenantProfile.java | 1 + .../microsoft/aad/msal4j/ThrottlingCache.java | 7 +- .../com/microsoft/aad/msal4j/TokenCache.java | 75 +++++++++--------- .../aad/msal4j/TokenCacheAccessContext.java | 2 +- .../aad/msal4j/TokenRequestExecutor.java | 9 +-- .../microsoft/aad/msal4j/TokenResponse.java | 6 +- .../microsoft/aad/msal4j/UserAssertion.java | 3 +- .../msal4j/UserNamePasswordParameters.java | 11 +-- .../aad/msal4j/UserNamePasswordRequest.java | 2 +- .../microsoft/aad/msal4j/WSTrustRequest.java | 14 ++-- .../microsoft/aad/msal4j/WSTrustResponse.java | 16 ++-- .../aad/msal4j/XmsClientTelemetryInfo.java | 16 ++-- .../aad/msal4j/AadInstanceDiscoveryTest.java | 8 +- .../com/microsoft/aad/msal4j/AccountTest.java | 10 ++- .../aad/msal4j/AcquireTokenSilentlyTest.java | 8 +- .../aad/msal4j/AssertionCredentialTest.java | 6 +- .../microsoft/aad/msal4j/AuthorityTest.java | 6 +- ...AuthorizationRequestUrlParametersTest.java | 12 +-- .../aad/msal4j/CacheFormatTests.java | 23 +++--- .../aad/msal4j/ClientCertificateTest.java | 4 +- .../aad/msal4j/DeviceCodeFlowTest.java | 24 +++--- .../microsoft/aad/msal4j/HttpUtilsTest.java | 14 ++-- .../microsoft/aad/msal4j/MexParserTest.java | 16 ++-- .../MsalOauthAuthorizatonGrantTest.java | 2 +- .../msal4j/OAuthRequestValidationTest.java | 2 +- .../aad/msal4j/OauthHttpRequestTest.java | 4 +- .../msal4j/PublicClientApplicationTest.java | 6 +- .../aad/msal4j/RequestThrottlingTest.java | 11 ++- .../aad/msal4j/ServerTelemetryTests.java | 52 ++++++------- .../microsoft/aad/msal4j/TelemetryTests.java | 62 +++++++-------- .../aad/msal4j/TestConfiguration.java | 4 +- .../aad/msal4j/TokenRequestExecutorTest.java | 19 +++-- .../aad/msal4j/TokenResponseTest.java | 5 +- .../aad/msal4j/WSTrustRequestTest.java | 7 +- .../aad/msal4j/WSTrustResponseTest.java | 12 +-- 162 files changed, 959 insertions(+), 969 deletions(-) diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenInteractiveIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenInteractiveIT.java index 73d3c2df..a3a9f386 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenInteractiveIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenInteractiveIT.java @@ -24,7 +24,7 @@ public class AcquireTokenInteractiveIT extends SeleniumTest { private Config cfg; @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenInteractive_ManagedUser(String environment){ + public void acquireTokenInteractive_ManagedUser(String environment) { cfg = new Config(environment); User user = labUserProvider.getDefaultUser(cfg.azureEnvironment); @@ -32,13 +32,13 @@ public void acquireTokenInteractive_ManagedUser(String environment){ } @Test() - public void acquireTokenInteractive_ADFSv2019_OnPrem(){ + public void acquireTokenInteractive_ADFSv2019_OnPrem() { User user = labUserProvider.getOnPremAdfsUser(FederationProvider.ADFS_2019); assertAcquireTokenADFS2019(user); } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenInteractive_ADFSv2019_Federated(String environment){ + public void acquireTokenInteractive_ADFSv2019_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_2019); @@ -46,7 +46,7 @@ public void acquireTokenInteractive_ADFSv2019_Federated(String environment){ } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenInteractive_ADFSv4_Federated(String environment){ + public void acquireTokenInteractive_ADFSv4_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_4); @@ -54,7 +54,7 @@ public void acquireTokenInteractive_ADFSv4_Federated(String environment){ } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenInteractive_ADFSv3_Federated(String environment){ + public void acquireTokenInteractive_ADFSv3_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_3); @@ -62,7 +62,7 @@ public void acquireTokenInteractive_ADFSv3_Federated(String environment){ } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenInteractive_ADFSv2_Federated(String environment){ + public void acquireTokenInteractive_ADFSv2_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_2); @@ -70,7 +70,7 @@ public void acquireTokenInteractive_ADFSv2_Federated(String environment){ } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_B2C_Local(String environment){ + public void acquireTokenWithAuthorizationCode_B2C_Local(String environment) { cfg = new Config(environment); User user = labUserProvider.getB2cUser(cfg.azureEnvironment, B2CProvider.LOCAL); @@ -78,21 +78,21 @@ public void acquireTokenWithAuthorizationCode_B2C_Local(String environment){ } @Test - public void acquireTokenInteractive_ManagedUser_InstanceAware(){ + public void acquireTokenInteractive_ManagedUser_InstanceAware() { cfg = new Config(AzureEnvironment.AZURE); User user = labUserProvider.getDefaultUser(AzureEnvironment.AZURE_US_GOVERNMENT); assertAcquireTokenInstanceAware(user); } - private void assertAcquireTokenAAD(User user){ + private void assertAcquireTokenAAD(User user) { PublicClientApplication pca; try { pca = PublicClientApplication.builder( user.getAppId()). authority(cfg.organizationsAuthority()). build(); - } catch(MalformedURLException ex){ + } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage()); } @@ -107,14 +107,14 @@ private void assertAcquireTokenAAD(User user){ Assert.assertEquals(user.getUpn(), result.account().username()); } - private void assertAcquireTokenADFS2019(User user){ + private void assertAcquireTokenADFS2019(User user) { PublicClientApplication pca; try { pca = PublicClientApplication.builder( TestConstants.ADFS_APP_ID). authority(TestConstants.ADFS_AUTHORITY). build(); - } catch(MalformedURLException ex){ + } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage()); } @@ -126,7 +126,7 @@ private void assertAcquireTokenADFS2019(User user){ Assert.assertEquals(user.getUpn(), result.account().username()); } - private void assertAcquireTokenB2C(User user){ + private void assertAcquireTokenB2C(User user) { PublicClientApplication pca; try { @@ -134,7 +134,7 @@ private void assertAcquireTokenB2C(User user){ user.getAppId()). b2cAuthority(TestConstants.B2C_AUTHORITY_SIGN_IN). build(); - } catch(MalformedURLException ex){ + } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage()); } @@ -189,10 +189,12 @@ public void acquireTokensInHomeAndGuestClouds(String homeCloud, String homeCloud ITokenCacheAccessAspect persistenceAspect = new ITokenCacheAccessAspect() { String data; + @Override public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { iTokenCacheAccessContext.tokenCache().deserialize(data); } + @Override public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { data = iTokenCacheAccessContext.tokenCache().serialize(); @@ -218,7 +220,7 @@ public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) private IAuthenticationResult acquireTokenInteractive( User user, PublicClientApplication pca, - String scope){ + String scope) { IAuthenticationResult result; try { @@ -238,7 +240,7 @@ private IAuthenticationResult acquireTokenInteractive( result = pca.acquireToken(parameters).get(); - } catch(Exception e){ + } catch (Exception e) { LOG.error("Error acquiring token with authCode: " + e.getMessage()); throw new RuntimeException("Error acquiring token with authCode: " + e.getMessage()); } @@ -248,7 +250,7 @@ private IAuthenticationResult acquireTokenInteractive( private IAuthenticationResult acquireTokenInteractive_instanceAware( User user, PublicClientApplication pca, - String scope){ + String scope) { IAuthenticationResult result; try { @@ -268,7 +270,7 @@ private IAuthenticationResult acquireTokenInteractive_instanceAware( result = pca.acquireToken(parameters).get(); - } catch(Exception e){ + } catch (Exception e) { LOG.error("Error acquiring token with authCode: " + e.getMessage()); throw new RuntimeException("Error acquiring token with authCode: " + e.getMessage()); } @@ -280,12 +282,12 @@ class SeleniumOpenBrowserAction implements OpenBrowserAction { private User user; private PublicClientApplication pca; - SeleniumOpenBrowserAction(User user, PublicClientApplication pca){ + SeleniumOpenBrowserAction(User user, PublicClientApplication pca) { this.user = user; this.pca = pca; } - public void openBrowser(URL url){ + public void openBrowser(URL url) { seleniumDriver.navigate().to(url); runSeleniumAutomatedLogin(user, pca); } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenSilentIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenSilentIT.java index ec06c645..8cd6b024 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenSilentIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/AcquireTokenSilentIT.java @@ -22,7 +22,7 @@ public class AcquireTokenSilentIT { private Config cfg; @BeforeClass - public void setUp(){ + public void setUp() { labUserProvider = LabUserProvider.getInstance(); } @@ -109,13 +109,13 @@ public void acquireTokenSilent_MultipleAccountsInCache_UseCorrectAccount(String } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenSilent_ADFS2019(String environment) throws Exception{ + public void acquireTokenSilent_ADFS2019(String environment) throws Exception { cfg = new Config(environment); UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); User user = labUserProvider.getLabUser(query); @@ -140,7 +140,7 @@ public void acquireTokenSilent_ADFS2019(String environment) throws Exception{ // Commented out due to unclear B2C behavior causing occasional errors //@Test - public void acquireTokenSilent_B2C() throws Exception{ + public void acquireTokenSilent_B2C() throws Exception { UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.USER_TYPE, UserType.B2C); query.parameters.put(UserQueryParameters.B2C_PROVIDER, B2CProvider.LOCAL); @@ -162,7 +162,6 @@ public void acquireTokenSilent_B2C() throws Exception{ } - @Test public void acquireTokenSilent_usingCommonAuthority_returnCachedAt() throws Exception { acquireTokenSilent_returnCachedTokens(cfg.organizationsAuthority()); @@ -174,7 +173,7 @@ public void acquireTokenSilent_usingTenantSpecificAuthority_returnCachedAt() thr } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenSilent_ConfidentialClient_acquireTokenSilent(String environment) throws Exception{ + public void acquireTokenSilent_ConfidentialClient_acquireTokenSilent(String environment) throws Exception { cfg = new Config(environment); IConfidentialClientApplication cca = getConfidentialClientApplications(); @@ -221,7 +220,7 @@ public void acquireTokenSilent_ConfidentialClient_acquireTokenSilentDifferentSco } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenSilent_WithRefreshOn(String environment) throws Exception{ + public void acquireTokenSilent_WithRefreshOn(String environment) throws Exception { cfg = new Config(environment); User user = labUserProvider.getDefaultUser(cfg.azureEnvironment); @@ -264,7 +263,7 @@ public void acquireTokenSilent_WithRefreshOn(String environment) throws Exceptio assertResultRefreshed(resultSilent, resultSilentWithRefreshOn); } - private IConfidentialClientApplication getConfidentialClientApplications() throws Exception{ + private IConfidentialClientApplication getConfidentialClientApplications() throws Exception { String clientId = cfg.appProvider.getOboAppId(); String password = cfg.appProvider.getOboAppPassword(); @@ -273,8 +272,8 @@ private IConfidentialClientApplication getConfidentialClientApplications() throw return ConfidentialClientApplication.builder( clientId, credential). //authority(MICROSOFT_AUTHORITY) - authority(cfg.tenantSpecificAuthority()). - build(); + authority(cfg.tenantSpecificAuthority()). + build(); } private void acquireTokenSilent_returnCachedTokens(String authority) throws Exception { diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/ApacheHttpClientAdapter.java b/src/integrationtest/java/com.microsoft.aad.msal4j/ApacheHttpClientAdapter.java index fd7261ef..89a84d08 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/ApacheHttpClientAdapter.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/ApacheHttpClientAdapter.java @@ -24,7 +24,7 @@ class ApacheHttpClientAdapter implements IHttpClient { private CloseableHttpClient httpClient; - ApacheHttpClientAdapter(){ + ApacheHttpClientAdapter() { this.httpClient = HttpClients.createDefault(); } @@ -38,31 +38,31 @@ public IHttpResponse send(HttpRequest httpRequest) throws Exception { } - private HttpRequestBase buildApacheRequestFromMsalRequest(HttpRequest httpRequest){ + private HttpRequestBase buildApacheRequestFromMsalRequest(HttpRequest httpRequest) { - if(httpRequest.httpMethod() == HttpMethod.GET){ + if (httpRequest.httpMethod() == HttpMethod.GET) { return builGetRequest(httpRequest); - } else if(httpRequest.httpMethod() == HttpMethod.POST){ + } else if (httpRequest.httpMethod() == HttpMethod.POST) { return buildPostRequest(httpRequest); } else { throw new IllegalArgumentException("HttpRequest method should be either GET or POST"); } } - private HttpGet builGetRequest(HttpRequest httpRequest){ + private HttpGet builGetRequest(HttpRequest httpRequest) { HttpGet httpGet = new HttpGet(httpRequest.url().toString()); - for(Map.Entry entry: httpRequest.headers().entrySet()){ + for (Map.Entry entry : httpRequest.headers().entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } return httpGet; } - private HttpPost buildPostRequest(HttpRequest httpRequest){ + private HttpPost buildPostRequest(HttpRequest httpRequest) { HttpPost httpPost = new HttpPost(httpRequest.url().toString()); - for(Map.Entry entry: httpRequest.headers().entrySet()){ + for (Map.Entry entry : httpRequest.headers().entrySet()) { httpPost.setHeader(entry.getKey(), entry.getValue()); } @@ -81,7 +81,7 @@ private IHttpResponse buildMsalResponseFromApacheResponse(CloseableHttpResponse ((HttpResponse) httpResponse).statusCode(apacheResponse.getStatusLine().getStatusCode()); Map> headers = new HashMap<>(); - for(Header header: apacheResponse.getAllHeaders()){ + for (Header header : apacheResponse.getAllHeaders()) { headers.put(header.getName(), Collections.singletonList(header.getValue())); } ((HttpResponse) httpResponse).addHeaders(headers); diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/AuthorizationCodeIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/AuthorizationCodeIT.java index fdf60c07..80058c8e 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/AuthorizationCodeIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/AuthorizationCodeIT.java @@ -25,7 +25,7 @@ public class AuthorizationCodeIT extends SeleniumTest { private Config cfg; @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ManagedUser(String environment){ + public void acquireTokenWithAuthorizationCode_ManagedUser(String environment) { cfg = new Config(environment); User user = labUserProvider.getDefaultUser(cfg.azureEnvironment); @@ -34,7 +34,7 @@ public void acquireTokenWithAuthorizationCode_ManagedUser(String environment){ //TODO: Re-enable test once list of claims/capabilities and their expected behavior is known //@Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ManagedUserWithClaimsAndCapabilities(String environment){ + public void acquireTokenWithAuthorizationCode_ManagedUserWithClaimsAndCapabilities(String environment) { cfg = new Config(environment); User user = labUserProvider.getDefaultUser(cfg.azureEnvironment); @@ -48,13 +48,13 @@ public void acquireTokenWithAuthorizationCode_ManagedUserWithClaimsAndCapabiliti } @Test - public void acquireTokenWithAuthorizationCode_ADFSv2019_OnPrem(){ + public void acquireTokenWithAuthorizationCode_ADFSv2019_OnPrem() { User user = labUserProvider.getOnPremAdfsUser(FederationProvider.ADFS_2019); assertAcquireTokenADFS2019(user); } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ADFSv2019_Federated(String environment){ + public void acquireTokenWithAuthorizationCode_ADFSv2019_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_2019); @@ -62,7 +62,7 @@ public void acquireTokenWithAuthorizationCode_ADFSv2019_Federated(String environ } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ADFSv4_Federated(String environment){ + public void acquireTokenWithAuthorizationCode_ADFSv4_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_4); @@ -71,7 +71,7 @@ public void acquireTokenWithAuthorizationCode_ADFSv4_Federated(String environmen } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ADFSv3_Federated(String environment){ + public void acquireTokenWithAuthorizationCode_ADFSv3_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_3); @@ -79,7 +79,7 @@ public void acquireTokenWithAuthorizationCode_ADFSv3_Federated(String environmen } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_ADFSv2_Federated(String environment){ + public void acquireTokenWithAuthorizationCode_ADFSv2_Federated(String environment) { cfg = new Config(environment); User user = labUserProvider.getFederatedAdfsUser(cfg.azureEnvironment, FederationProvider.ADFS_2); @@ -87,7 +87,7 @@ public void acquireTokenWithAuthorizationCode_ADFSv2_Federated(String environmen } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithAuthorizationCode_B2C_Local(String environment){ + public void acquireTokenWithAuthorizationCode_B2C_Local(String environment) { cfg = new Config(environment); User user = labUserProvider.getB2cUser(environment, B2CProvider.LOCAL); @@ -97,7 +97,7 @@ public void acquireTokenWithAuthorizationCode_B2C_Local(String environment){ // failing on azure devOps //@Test // TODO Redirect URI localhost in not registered - public void acquireTokenWithAuthorizationCode_B2C_Google(){ + public void acquireTokenWithAuthorizationCode_B2C_Google() { /* LabResponse labResponse = labUserProvider.getB2cUser( B2CIdentityProvider.GOOGLE, false); @@ -112,7 +112,7 @@ public void acquireTokenWithAuthorizationCode_B2C_Google(){ // TODO uncomment when lab fixes facebook test account //@Test // TODO Redirect URI localhost in not registered - public void acquireTokenWithAuthorizationCode_B2C_Facebook(){ + public void acquireTokenWithAuthorizationCode_B2C_Facebook() { /* LabResponse labResponse = labUserProvider.getB2cUser( B2CIdentityProvider.FACEBOOK, false); @@ -125,14 +125,14 @@ public void acquireTokenWithAuthorizationCode_B2C_Facebook(){ assertAcquireTokenB2C(user); } - private void assertAcquireTokenADFS2019(User user){ + private void assertAcquireTokenADFS2019(User user) { PublicClientApplication pca; try { - pca = PublicClientApplication.builder( + pca = PublicClientApplication.builder( TestConstants.ADFS_APP_ID). authority(TestConstants.ADFS_AUTHORITY). build(); - } catch(MalformedURLException ex){ + } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage()); } @@ -148,7 +148,7 @@ private void assertAcquireTokenADFS2019(User user){ Assert.assertEquals(user.getUpn(), result.account().username()); } - private void assertAcquireTokenAAD(User user, Map> parameters){ + private void assertAcquireTokenAAD(User user, Map> parameters) { PublicClientApplication pca; Set clientCapabilities = null; @@ -156,12 +156,12 @@ private void assertAcquireTokenAAD(User user, Map> parameter clientCapabilities = parameters.getOrDefault("clientCapabilities", null); } try { - pca = PublicClientApplication.builder( - user.getAppId()). - authority(cfg.organizationsAuthority()). - clientCapabilities(clientCapabilities). - build(); - } catch(MalformedURLException ex){ + pca = PublicClientApplication.builder( + user.getAppId()). + authority(cfg.organizationsAuthority()). + clientCapabilities(clientCapabilities). + build(); + } catch (MalformedURLException ex) { throw new RuntimeException(ex.getMessage()); } @@ -177,7 +177,7 @@ private void assertAcquireTokenAAD(User user, Map> parameter Assert.assertEquals(user.getUpn(), result.account().username()); } - private void assertAcquireTokenB2C(User user){ + private void assertAcquireTokenB2C(User user) { String appId = LabService.getSecret(TestConstants.B2C_CONFIDENTIAL_CLIENT_LAB_APP_ID); String appSecret = LabService.getSecret(TestConstants.B2C_CONFIDENTIAL_CLIENT_APP_SECRETID); @@ -189,7 +189,7 @@ private void assertAcquireTokenB2C(User user){ .builder(appId, credential) .b2cAuthority(TestConstants.B2C_AUTHORITY_SIGN_IN) .build(); - } catch(Exception ex){ + } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } @@ -204,7 +204,7 @@ private void assertAcquireTokenB2C(User user){ private IAuthenticationResult acquireTokenAuthorizationCodeFlow( PublicClientApplication pca, String authCode, - Set scopes){ + Set scopes) { IAuthenticationResult result; try { @@ -215,7 +215,7 @@ private IAuthenticationResult acquireTokenAuthorizationCodeFlow( .build()) .get(); - } catch(Exception e){ + } catch (Exception e) { LOG.error("Error acquiring token with authCode: " + e.getMessage()); throw new RuntimeException("Error acquiring token with authCode: " + e.getMessage()); } @@ -223,15 +223,15 @@ private IAuthenticationResult acquireTokenAuthorizationCodeFlow( } private IAuthenticationResult acquireTokenInteractiveB2C(ConfidentialClientApplication cca, - String authCode) { + String authCode) { IAuthenticationResult result; - try{ + try { result = cca.acquireToken(AuthorizationCodeParameters .builder(authCode, new URI(TestConstants.LOCALHOST + httpListener.port())) .scopes(Collections.singleton(TestConstants.B2C_LAB_SCOPE)) .build()) .get(); - } catch (Exception e){ + } catch (Exception e) { LOG.error("Error acquiring token with authCode: " + e.getMessage()); throw new RuntimeException("Error acquiring token with authCode: " + e.getMessage()); } @@ -241,7 +241,7 @@ private IAuthenticationResult acquireTokenInteractiveB2C(ConfidentialClientAppli private String acquireAuthorizationCodeAutomated( User user, AbstractClientApplicationBase app, - Map> parameters){ + Map> parameters) { BlockingQueue authorizationCodeQueue = new LinkedBlockingQueue<>(); @@ -260,15 +260,15 @@ private String acquireAuthorizationCodeAutomated( long expirationTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + 120; - while(result == null && + while (result == null && TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) < expirationTime) { result = authorizationCodeQueue.poll(100, TimeUnit.MILLISECONDS); } - } catch(Exception e){ + } catch (Exception e) { throw new MsalClientException(e); } finally { - if(httpListener != null){ + if (httpListener != null) { httpListener.stopListener(); } } @@ -288,16 +288,14 @@ private String buildAuthenticationCodeURL(AbstractClientApplicationBase app, Map claims = String.valueOf(parameters.getOrDefault("claims", Collections.singleton("")).toArray()[0]); } - AuthorityType authorityType= app.authenticationAuthority.authorityType; - if(authorityType == AuthorityType.AAD){ + AuthorityType authorityType = app.authenticationAuthority.authorityType; + if (authorityType == AuthorityType.AAD) { scope = TestConstants.GRAPH_DEFAULT_SCOPE; } else if (authorityType == AuthorityType.B2C) { scope = TestConstants.B2C_LAB_SCOPE; - } - else if (authorityType == AuthorityType.ADFS){ + } else if (authorityType == AuthorityType.ADFS) { scope = TestConstants.ADFS_SCOPE; - } - else{ + } else { throw new RuntimeException("Authority type not recognized"); } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/AzureEnvironmentIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/AzureEnvironmentIT.java index aa44f722..04f2993f 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/AzureEnvironmentIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/AzureEnvironmentIT.java @@ -33,7 +33,7 @@ public void acquireTokenWithUsernamePassword_AzureGovernment() throws Exception assertAcquireTokenCommon(AzureEnvironment.AZURE_US_GOVERNMENT); } - private void assertAcquireTokenCommon(String azureEnvironment) throws Exception{ + private void assertAcquireTokenCommon(String azureEnvironment) throws Exception { User user = labUserProvider.getUserByAzureEnvironment(azureEnvironment); App app = LabService.getApp(user.getAppId()); @@ -44,10 +44,10 @@ private void assertAcquireTokenCommon(String azureEnvironment) throws Exception{ build(); IAuthenticationResult result = pca.acquireToken(UserNamePasswordParameters - .builder(Collections.singleton(TestConstants.USER_READ_SCOPE), - user.getUpn(), - user.getPassword().toCharArray()) - .build()) + .builder(Collections.singleton(TestConstants.USER_READ_SCOPE), + user.getUpn(), + user.getPassword().toCharArray()) + .build()) .get(); Assert.assertNotNull(result); diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/CachePersistenceIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/CachePersistenceIT.java index 0717e0c9..f943a946 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/CachePersistenceIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/CachePersistenceIT.java @@ -13,15 +13,15 @@ public class CachePersistenceIT { - static class TokenPersistence implements ITokenCacheAccessAspect{ + static class TokenPersistence implements ITokenCacheAccessAspect { String data; - TokenPersistence(String data){ + TokenPersistence(String data) { this.data = data; } @Override - public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext){ + public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { iTokenCacheAccessContext.tokenCache().deserialize(data); } @@ -50,7 +50,7 @@ public void cacheDeserializationSerializationTest() throws IOException, URISynta PublicClientApplication app = PublicClientApplication.builder("my_client_id") .setTokenCacheAccessAspect(persistenceAspect).build(); - Assert.assertEquals(app.getAccounts().join().size() , 1); + Assert.assertEquals(app.getAccounts().join().size(), 1); Assert.assertEquals(app.tokenCache.accounts.size(), 1); Assert.assertEquals(app.tokenCache.accessTokens.size(), 2); Assert.assertEquals(app.tokenCache.refreshTokens.size(), 1); @@ -61,7 +61,7 @@ public void cacheDeserializationSerializationTest() throws IOException, URISynta app = PublicClientApplication.builder("my_client_id") .setTokenCacheAccessAspect(persistenceAspect).build(); - Assert.assertEquals(app.getAccounts().join().size() , 1); + Assert.assertEquals(app.getAccounts().join().size(), 1); Assert.assertEquals(app.tokenCache.accounts.size(), 1); Assert.assertEquals(app.tokenCache.accessTokens.size(), 2); Assert.assertEquals(app.tokenCache.refreshTokens.size(), 1); @@ -70,7 +70,7 @@ public void cacheDeserializationSerializationTest() throws IOException, URISynta app.removeAccount(app.getAccounts().join().iterator().next()).join(); - Assert.assertEquals(app.getAccounts().join().size() , 0); + Assert.assertEquals(app.getAccounts().join().size(), 0); Assert.assertEquals(app.tokenCache.accounts.size(), 0); Assert.assertEquals(app.tokenCache.accessTokens.size(), 1); Assert.assertEquals(app.tokenCache.refreshTokens.size(), 0); @@ -80,7 +80,7 @@ public void cacheDeserializationSerializationTest() throws IOException, URISynta app = PublicClientApplication.builder("my_client_id") .setTokenCacheAccessAspect(persistenceAspect).build(); - Assert.assertEquals(app.getAccounts().join().size() , 0); + Assert.assertEquals(app.getAccounts().join().size(), 0); Assert.assertEquals(app.tokenCache.accounts.size(), 0); Assert.assertEquals(app.tokenCache.accessTokens.size(), 1); Assert.assertEquals(app.tokenCache.refreshTokens.size(), 0); diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/CertificateHelper.java b/src/integrationtest/java/com.microsoft.aad.msal4j/CertificateHelper.java index 9d9fd082..c3381a3a 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/CertificateHelper.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/CertificateHelper.java @@ -14,10 +14,9 @@ public class CertificateHelper { static KeyStore createKeyStore() throws KeyStoreException, NoSuchProviderException { String os = SystemUtils.OS_NAME; - if(os.contains("Mac")){ + if (os.contains("Mac")) { return KeyStore.getInstance("KeychainStore"); - } - else{ + } else { return KeyStore.getInstance("Windows-MY", "SunMSCAPI"); } } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/ClientCredentialsIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/ClientCredentialsIT.java index e8c38919..5c8b5928 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/ClientCredentialsIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/ClientCredentialsIT.java @@ -29,13 +29,13 @@ void init() throws CertificateException, UnrecoverableKeyException, NoSuchAlgori } @Test - public void acquireTokenClientCredentials_ClientCertificate() throws Exception{ + public void acquireTokenClientCredentials_ClientCertificate() throws Exception { String clientId = "55e7e5af-ca53-482d-9aa3-5cb1cc8eecb5"; assertAcquireTokenCommon(clientId, certificate); } @Test - public void acquireTokenClientCredentials_ClientSecret() throws Exception{ + public void acquireTokenClientCredentials_ClientSecret() throws Exception { AppCredentialProvider appProvider = new AppCredentialProvider(AzureEnvironment.AZURE); final String clientId = appProvider.getLabVaultAppId(); final String password = appProvider.getLabVaultPassword(); @@ -45,7 +45,7 @@ public void acquireTokenClientCredentials_ClientSecret() throws Exception{ } @Test - public void acquireTokenClientCredentials_ClientAssertion() throws Exception{ + public void acquireTokenClientCredentials_ClientAssertion() throws Exception { String clientId = "55e7e5af-ca53-482d-9aa3-5cb1cc8eecb5"; ClientAssertion clientAssertion = JwtHelper.buildJwt( @@ -61,7 +61,7 @@ public void acquireTokenClientCredentials_ClientAssertion() throws Exception{ } @Test - public void acquireTokenClientCredentials_DefaultCacheLookup() throws Exception{ + public void acquireTokenClientCredentials_DefaultCacheLookup() throws Exception { AppCredentialProvider appProvider = new AppCredentialProvider(AzureEnvironment.AZURE); final String clientId = appProvider.getLabVaultAppId(); final String password = appProvider.getLabVaultPassword(); @@ -99,7 +99,7 @@ public void acquireTokenClientCredentials_DefaultCacheLookup() throws Exception{ } - private void assertAcquireTokenCommon(String clientId, IClientCredential credential) throws Exception{ + private void assertAcquireTokenCommon(String clientId, IClientCredential credential) throws Exception { ConfidentialClientApplication cca = ConfidentialClientApplication.builder( clientId, credential). authority(TestConstants.MICROSOFT_AUTHORITY). diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/ConfidentialClientApplicationUnitT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/ConfidentialClientApplicationUnitT.java index bfef31e4..2836abe0 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/ConfidentialClientApplicationUnitT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/ConfidentialClientApplicationUnitT.java @@ -144,7 +144,7 @@ public void testAcquireToken_KeyCred() throws Exception { @Test public void testClientCertificateRebuildsWhenExpired() throws Exception { - PowerMock.mockStaticPartial(JwtHelper.class, new String[]{"buildJwt"}); + PowerMock.mockStaticPartial(JwtHelper.class, "buildJwt"); long jwtExperiationPeriodMilli = 2000; ClientAssertion shortExperationJwt = buildShortJwt(TestConfiguration.AAD_CLIENT_ID, clientCertificate, diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/Config.java b/src/integrationtest/java/com.microsoft.aad.msal4j/Config.java index 7225f3a7..7cf982f2 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/Config.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/Config.java @@ -18,17 +18,17 @@ public class Config { String azureEnvironment; - Config (String azureEnvironment){ + Config(String azureEnvironment) { this.azureEnvironment = azureEnvironment; - switch (azureEnvironment){ + switch (azureEnvironment) { case AzureEnvironment.AZURE: organizationsAuthority = TestConstants.ORGANIZATIONS_AUTHORITY; tenantSpecificAuthority = TestConstants.TENANT_SPECIFIC_AUTHORITY; graphDefaultScope = TestConstants.GRAPH_DEFAULT_SCOPE; appProvider = new AppCredentialProvider(azureEnvironment); break; - case AzureEnvironment.AZURE_US_GOVERNMENT : + case AzureEnvironment.AZURE_US_GOVERNMENT: organizationsAuthority = TestConstants.ARLINGTON_ORGANIZATIONS_AUTHORITY; tenantSpecificAuthority = TestConstants.ARLINGTON_TENANT_SPECIFIC_AUTHORITY; graphDefaultScope = TestConstants.ARLINGTON_GRAPH_DEFAULT_SCOPE; diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/DeviceCodeIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/DeviceCodeIT.java index 4496d767..2feb84ed 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/DeviceCodeIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/DeviceCodeIT.java @@ -29,7 +29,7 @@ public class DeviceCodeIT { private Config cfg; @BeforeClass - public void setUp(){ + public void setUp() { labUserProvider = LabUserProvider.getInstance(); seleniumDriver = SeleniumExtensions.createDefaultWebDriver(); } @@ -43,7 +43,7 @@ public void DeviceCodeFlowADTest(String environment) throws Exception { PublicClientApplication pca = PublicClientApplication.builder( user.getAppId()). authority(cfg.tenantSpecificAuthority()). - build(); + build(); Consumer deviceCodeConsumer = (DeviceCode deviceCode) -> { runAutomatedDeviceCodeFlow(deviceCode, user, environment); @@ -83,17 +83,17 @@ public void DeviceCodeFlowADFSv2019Test(String environment) throws Exception { Assert.assertFalse(Strings.isNullOrEmpty(result.accessToken())); } - private void runAutomatedDeviceCodeFlow(DeviceCode deviceCode, User user, String environment){ + private void runAutomatedDeviceCodeFlow(DeviceCode deviceCode, User user, String environment) { boolean isRunningLocally = true;//!Strings.isNullOrEmpty( - //System.getenv(TestConstants.LOCAL_FLAG_ENV_VAR)); + //System.getenv(TestConstants.LOCAL_FLAG_ENV_VAR)); boolean isADFS2019 = user.getFederationProvider().equals("adfsv2019"); LOG.info("Device code running locally: " + isRunningLocally); - try{ + try { String deviceCodeFormId; String continueButtonId; - if(isRunningLocally){ + if (isRunningLocally) { if (isADFS2019) { deviceCodeFormId = "userCodeInput"; continueButtonId = "confirmationButton"; @@ -114,8 +114,8 @@ private void runAutomatedDeviceCodeFlow(DeviceCode deviceCode, User user, String LOG.info("Loggin in ... click continue"); WebElement continueBtn = SeleniumExtensions.waitForElementToBeVisibleAndEnable( - seleniumDriver, - new By.ById(continueButtonId)); + seleniumDriver, + new By.ById(continueButtonId)); continueBtn.click(); if (isADFS2019) { @@ -123,8 +123,8 @@ private void runAutomatedDeviceCodeFlow(DeviceCode deviceCode, User user, String } else { SeleniumExtensions.performADLogin(seleniumDriver, user); } - } catch(Exception e){ - if(!isRunningLocally){ + } catch (Exception e) { + if (!isRunningLocally) { SeleniumExtensions.takeScreenShot(seleniumDriver); } LOG.error("Browser automation failed: " + e.getMessage()); @@ -133,8 +133,8 @@ private void runAutomatedDeviceCodeFlow(DeviceCode deviceCode, User user, String } @AfterClass - public void cleanUp(){ - if( seleniumDriver != null){ + public void cleanUp() { + if (seleniumDriver != null) { seleniumDriver.close(); } } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/EnvironmentsProvider.java b/src/integrationtest/java/com.microsoft.aad.msal4j/EnvironmentsProvider.java index bdcf40eb..22b40ff2 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/EnvironmentsProvider.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/EnvironmentsProvider.java @@ -9,8 +9,8 @@ public class EnvironmentsProvider { @DataProvider(name = "environments") public static Object[][] createData() { - return new Object[][] { - { AzureEnvironment.AZURE }, - { AzureEnvironment.AZURE_US_GOVERNMENT }}; + return new Object[][]{ + {AzureEnvironment.AZURE}, + {AzureEnvironment.AZURE_US_GOVERNMENT}}; } } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/HttpClientIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/HttpClientIT.java index 4fb5c62e..6c800168 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/HttpClientIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/HttpClientIT.java @@ -33,7 +33,7 @@ public void acquireToken_apacheHttpClient() throws Exception { } private void assertAcquireTokenCommon(User user, IHttpClient httpClient) - throws Exception{ + throws Exception { PublicClientApplication pca = PublicClientApplication.builder( user.getAppId()). authority(TestConstants.ORGANIZATIONS_AUTHORITY). diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/OkHttpClientAdapter.java b/src/integrationtest/java/com.microsoft.aad.msal4j/OkHttpClientAdapter.java index bcfb958a..d2ec8f46 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/OkHttpClientAdapter.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/OkHttpClientAdapter.java @@ -13,11 +13,11 @@ import java.io.IOException; -class OkHttpClientAdapter implements IHttpClient{ +class OkHttpClientAdapter implements IHttpClient { private OkHttpClient client; - OkHttpClientAdapter(){ + OkHttpClientAdapter() { this.client = new OkHttpClient(); } @@ -26,22 +26,22 @@ public IHttpResponse send(HttpRequest httpRequest) throws IOException { Request request = buildOkRequestFromMsalRequest(httpRequest); - Response okHttpResponse= client.newCall(request).execute(); + Response okHttpResponse = client.newCall(request).execute(); return buildMsalResponseFromOkResponse(okHttpResponse); } - private Request buildOkRequestFromMsalRequest(HttpRequest httpRequest){ + private Request buildOkRequestFromMsalRequest(HttpRequest httpRequest) { - if(httpRequest.httpMethod() == HttpMethod.GET){ + if (httpRequest.httpMethod() == HttpMethod.GET) { return buildGetRequest(httpRequest); - } else if(httpRequest.httpMethod() == HttpMethod.POST){ + } else if (httpRequest.httpMethod() == HttpMethod.POST) { return buildPostRequest(httpRequest); } else { throw new IllegalArgumentException("HttpRequest method should be either GET or POST"); } } - private Request buildGetRequest(HttpRequest httpRequest){ + private Request buildGetRequest(HttpRequest httpRequest) { Headers headers = Headers.of(httpRequest.headers()); return new Request.Builder() @@ -50,7 +50,7 @@ private Request buildGetRequest(HttpRequest httpRequest){ .build(); } - private Request buildPostRequest(HttpRequest httpRequest){ + private Request buildPostRequest(HttpRequest httpRequest) { Headers headers = Headers.of(httpRequest.headers()); String contentType = httpRequest.headerValue("Content-Type"); MediaType type = MediaType.parse(contentType); @@ -64,18 +64,18 @@ private Request buildPostRequest(HttpRequest httpRequest){ .build(); } - private IHttpResponse buildMsalResponseFromOkResponse(Response okHttpResponse) throws IOException{ + private IHttpResponse buildMsalResponseFromOkResponse(Response okHttpResponse) throws IOException { IHttpResponse httpResponse = new HttpResponse(); ((HttpResponse) httpResponse).statusCode(okHttpResponse.code()); ResponseBody body = okHttpResponse.body(); - if(body != null){ + if (body != null) { ((HttpResponse) httpResponse).body(body.string()); } Headers headers = okHttpResponse.headers(); - if(headers != null){ + if (headers != null) { ((HttpResponse) httpResponse).addHeaders(headers.toMultimap()); } return httpResponse; diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/OnBehalfOfIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/OnBehalfOfIT.java index 3c7e6bae..71d706c3 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/OnBehalfOfIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/OnBehalfOfIT.java @@ -92,8 +92,8 @@ public void acquireTokenWithOBO_testCache(String environment) throws Exception { IAuthenticationResult result5 = cca.acquireToken( OnBehalfOfParameters.builder( - Collections.singleton(cfg.graphDefaultScope()), - new UserAssertion(accessToken)) + Collections.singleton(cfg.graphDefaultScope()), + new UserAssertion(accessToken)) .skipCache(true) .build()). get(); @@ -127,7 +127,7 @@ private String getAccessToken() throws Exception { User user = labUserProvider.getDefaultUser(cfg.azureEnvironment); String clientId = cfg.appProvider.getAppId(); - String apiReadScope = cfg.appProvider.getOboAppIdURI() + "/user_impersonation"; + String apiReadScope = cfg.appProvider.getOboAppIdURI() + "/user_impersonation"; PublicClientApplication pca = PublicClientApplication.builder( clientId). authority(cfg.tenantSpecificAuthority()). diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/RefreshTokenIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/RefreshTokenIT.java index 1b39e29b..f4efe5f0 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/RefreshTokenIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/RefreshTokenIT.java @@ -30,18 +30,18 @@ private void setUp(String environment) throws Exception { authority(cfg.organizationsAuthority()). build(); - AuthenticationResult result = (AuthenticationResult)pca.acquireToken(UserNamePasswordParameters - .builder(Collections.singleton(cfg.graphDefaultScope()), - user.getUpn(), - user.getPassword().toCharArray()) - .build()) + AuthenticationResult result = (AuthenticationResult) pca.acquireToken(UserNamePasswordParameters + .builder(Collections.singleton(cfg.graphDefaultScope()), + user.getUpn(), + user.getPassword().toCharArray()) + .build()) .get(); refreshToken = result.refreshToken(); } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithRefreshToken(String environment) throws Exception{ + public void acquireTokenWithRefreshToken(String environment) throws Exception { cfg = new Config(environment); setUp(environment); @@ -59,7 +59,7 @@ public void acquireTokenWithRefreshToken(String environment) throws Exception{ } @Test(expectedExceptions = ExecutionException.class) - public void acquireTokenWithRefreshToken_WrongScopes() throws Exception{ + public void acquireTokenWithRefreshToken_WrongScopes() throws Exception { IAuthenticationResult result = pca.acquireToken(RefreshTokenParameters .builder( Collections.singleton(TestConstants.KEYVAULT_DEFAULT_SCOPE), diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/SeleniumTest.java b/src/integrationtest/java/com.microsoft.aad.msal4j/SeleniumTest.java index 90f7f47c..62306e12 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/SeleniumTest.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/SeleniumTest.java @@ -24,22 +24,22 @@ public void setUpLapUserProvider() { } @AfterMethod - public void cleanUp(){ + public void cleanUp() { seleniumDriver.quit(); - if(httpListener != null) { + if (httpListener != null) { httpListener.stopListener(); } } @BeforeMethod - public void startUpBrowser(){ + public void startUpBrowser() { seleniumDriver = SeleniumExtensions.createDefaultWebDriver(); } void runSeleniumAutomatedLogin(User user, AbstractClientApplicationBase app) { AuthorityType authorityType = app.authenticationAuthority.authorityType; - if(authorityType == AuthorityType.B2C){ - switch(user.getB2cProvider().toLowerCase()){ + if (authorityType == AuthorityType.B2C) { + switch (user.getB2cProvider().toLowerCase()) { case B2CProvider.LOCAL: SeleniumExtensions.performLocalLogin(seleniumDriver, user); break; @@ -52,8 +52,7 @@ void runSeleniumAutomatedLogin(User user, AbstractClientApplicationBase app) { } } else if (authorityType == AuthorityType.AAD) { SeleniumExtensions.performADLogin(seleniumDriver, user); - } - else if (authorityType == AuthorityType.ADFS) { + } else if (authorityType == AuthorityType.ADFS) { SeleniumExtensions.performADFS2019Login(seleniumDriver, user); } } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/TokenCacheIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/TokenCacheIT.java index 17793ff9..66bd6f90 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/TokenCacheIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/TokenCacheIT.java @@ -30,7 +30,7 @@ public void singleAccountInCache_RemoveAccountTest() throws Exception { build(); // Check that cache is empty - Assert.assertEquals(pca.getAccounts().join().size() , 0); + Assert.assertEquals(pca.getAccounts().join().size(), 0); pca.acquireToken(UserNamePasswordParameters. builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE), @@ -49,7 +49,7 @@ public void singleAccountInCache_RemoveAccountTest() throws Exception { } @Test - public void twoAccountsInCache_RemoveAccountTest() throws Exception{ + public void twoAccountsInCache_RemoveAccountTest() throws Exception { User managedUser = labUserProvider.getDefaultUser(); @@ -58,7 +58,7 @@ public void twoAccountsInCache_RemoveAccountTest() throws Exception{ authority(TestConstants.ORGANIZATIONS_AUTHORITY). build(); - Assert.assertEquals(pca.getAccounts().join().size() , 0); + Assert.assertEquals(pca.getAccounts().join().size(), 0); pca.acquireToken(UserNamePasswordParameters. builder(Collections.singleton(TestConstants.GRAPH_DEFAULT_SCOPE), @@ -67,7 +67,7 @@ public void twoAccountsInCache_RemoveAccountTest() throws Exception{ .build()) .get(); - Assert.assertEquals(pca.getAccounts().join().size() , 1); + Assert.assertEquals(pca.getAccounts().join().size(), 1); // get lab user for different account User adfsUser = labUserProvider.getFederatedAdfsUser(FederationProvider.ADFS_4); @@ -89,7 +89,7 @@ public void twoAccountsInCache_RemoveAccountTest() throws Exception{ pca.removeAccount(accountLabResponse1).join(); - Assert.assertEquals(pca.getAccounts().join().size() , 1); + Assert.assertEquals(pca.getAccounts().join().size(), 1); IAccount accountLabResponse2 = pca.getAccounts().get().iterator().next(); @@ -98,12 +98,12 @@ public void twoAccountsInCache_RemoveAccountTest() throws Exception{ } @Test - public void twoAccountsInCache_SameUserDifferentTenants_RemoveAccountTest() throws Exception{ + public void twoAccountsInCache_SameUserDifferentTenants_RemoveAccountTest() throws Exception { UserQueryParameters query = new UserQueryParameters(); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.GUEST); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.GUEST); - User guestUser = labUserProvider.getLabUser(query); + User guestUser = labUserProvider.getLabUser(query); Lab lab = LabService.getLab(guestUser.getLabName()); String dataToInitCache = TestHelper.readResource( @@ -146,14 +146,14 @@ public void twoAccountsInCache_SameUserDifferentTenants_RemoveAccountTest() thro .get(); // There should be two tokens in cache, with same accounts except for tenant - Assert.assertEquals(pca2.getAccounts().join().iterator().next().getTenantProfiles().size() , 2); + Assert.assertEquals(pca2.getAccounts().join().iterator().next().getTenantProfiles().size(), 2); IAccount account = pca2.getAccounts().get().iterator().next(); // RemoveAccount should remove both cache entities pca2.removeAccount(account).join(); - Assert.assertEquals(pca.getAccounts().join().size() , 0); + Assert.assertEquals(pca.getAccounts().join().size(), 0); //clean up file TestHelper.deleteFileContent( @@ -161,15 +161,15 @@ public void twoAccountsInCache_SameUserDifferentTenants_RemoveAccountTest() thro "/cache_data/remove-account-test-cache.json"); } - private static class TokenPersistence implements ITokenCacheAccessAspect{ + private static class TokenPersistence implements ITokenCacheAccessAspect { String data; - TokenPersistence(String data){ + TokenPersistence(String data) { this.data = data; } @Override - public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext){ + public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) { iTokenCacheAccessContext.tokenCache().deserialize(data); } diff --git a/src/integrationtest/java/com.microsoft.aad.msal4j/UsernamePasswordIT.java b/src/integrationtest/java/com.microsoft.aad.msal4j/UsernamePasswordIT.java index b0b2c69f..d4bcc601 100644 --- a/src/integrationtest/java/com.microsoft.aad.msal4j/UsernamePasswordIT.java +++ b/src/integrationtest/java/com.microsoft.aad.msal4j/UsernamePasswordIT.java @@ -31,13 +31,13 @@ public void acquireTokenWithUsernamePassword_Managed(String environment) throws } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithUsernamePassword_ADFSv2019_Federated(String environment) throws Exception{ + public void acquireTokenWithUsernamePassword_ADFSv2019_Federated(String environment) throws Exception { cfg = new Config(environment); UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); User user = labUserProvider.getLabUser(query); @@ -45,10 +45,10 @@ public void acquireTokenWithUsernamePassword_ADFSv2019_Federated(String environm } @Test - public void acquireTokenWithUsernamePassword_ADFSv2019_OnPrem() throws Exception{ + public void acquireTokenWithUsernamePassword_ADFSv2019_OnPrem() throws Exception { UserQueryParameters query = new UserQueryParameters(); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.ON_PREM); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2019); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.ON_PREM); User user = labUserProvider.getLabUser(query); @@ -56,13 +56,13 @@ public void acquireTokenWithUsernamePassword_ADFSv2019_OnPrem() throws Exception } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithUsernamePassword_ADFSv4(String environment) throws Exception{ + public void acquireTokenWithUsernamePassword_ADFSv4(String environment) throws Exception { cfg = new Config(environment); UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_4); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_4); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); User user = labUserProvider.getLabUser(query); @@ -70,13 +70,13 @@ public void acquireTokenWithUsernamePassword_ADFSv4(String environment) throws E } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithUsernamePassword_ADFSv3(String environment) throws Exception{ + public void acquireTokenWithUsernamePassword_ADFSv3(String environment) throws Exception { cfg = new Config(environment); UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_3); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_3); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); User user = labUserProvider.getLabUser(query); @@ -84,13 +84,13 @@ public void acquireTokenWithUsernamePassword_ADFSv3(String environment) throws E } @Test(dataProvider = "environments", dataProviderClass = EnvironmentsProvider.class) - public void acquireTokenWithUsernamePassword_ADFSv2(String environment) throws Exception{ + public void acquireTokenWithUsernamePassword_ADFSv2(String environment) throws Exception { cfg = new Config(environment); UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, cfg.azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, FederationProvider.ADFS_2); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); User user = labUserProvider.getLabUser(query); @@ -108,7 +108,7 @@ private void assertAcquireTokenCommonAAD(User user) throws Exception { } private void assertAcquireTokenCommon(User user, String authority, String scope, String appId) - throws Exception{ + throws Exception { PublicClientApplication pca = PublicClientApplication.builder( appId). authority(authority). @@ -128,7 +128,7 @@ private void assertAcquireTokenCommon(User user, String authority, String scope, } @Test - public void acquireTokenWithUsernamePassword_B2C_CustomAuthority() throws Exception{ + public void acquireTokenWithUsernamePassword_B2C_CustomAuthority() throws Exception { UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.USER_TYPE, UserType.B2C); query.parameters.put(UserQueryParameters.B2C_PROVIDER, B2CProvider.LOCAL); @@ -155,7 +155,7 @@ public void acquireTokenWithUsernamePassword_B2C_CustomAuthority() throws Except result = pca.acquireTokenSilently( SilentParameters.builder(Collections.singleton(TestConstants.B2C_READ_SCOPE), account) - .build()) + .build()) .get(); Assert.assertNotNull(result); @@ -164,7 +164,7 @@ public void acquireTokenWithUsernamePassword_B2C_CustomAuthority() throws Except } @Test - public void acquireTokenWithUsernamePassword_B2C_LoginMicrosoftOnline() throws Exception{ + public void acquireTokenWithUsernamePassword_B2C_LoginMicrosoftOnline() throws Exception { UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.USER_TYPE, UserType.B2C); query.parameters.put(UserQueryParameters.B2C_PROVIDER, B2CProvider.LOCAL); diff --git a/src/integrationtest/java/infrastructure/SeleniumExtensions.java b/src/integrationtest/java/infrastructure/SeleniumExtensions.java index b4aaae49..f7084c01 100644 --- a/src/integrationtest/java/infrastructure/SeleniumExtensions.java +++ b/src/integrationtest/java/infrastructure/SeleniumExtensions.java @@ -28,9 +28,10 @@ public class SeleniumExtensions { private final static Logger LOG = LoggerFactory.getLogger(SeleniumExtensions.class); - private SeleniumExtensions(){} + private SeleniumExtensions() { + } - public static WebDriver createDefaultWebDriver(){ + public static WebDriver createDefaultWebDriver() { ChromeOptions options = new ChromeOptions(); //no visual rendering, remove when debugging options.addArguments("--headless"); @@ -40,7 +41,7 @@ public static WebDriver createDefaultWebDriver(){ driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return driver; -} + } public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By by, int timeOutInSeconds) { WebDriverWait webDriverWait = new WebDriverWait(driver, timeOutInSeconds); @@ -48,7 +49,7 @@ public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By { try { WebElement elementToBeDisplayed = driver.findElement(by); - if(elementToBeDisplayed.isDisplayed() && elementToBeDisplayed.isEnabled()){ + if (elementToBeDisplayed.isDisplayed() && elementToBeDisplayed.isEnabled()) { return elementToBeDisplayed; } return null; @@ -58,13 +59,13 @@ public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By }); } - public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By by){ + public static WebElement waitForElementToBeVisibleAndEnable(WebDriver driver, By by) { int DEFAULT_TIMEOUT_IN_SEC = 15; return waitForElementToBeVisibleAndEnable(driver, by, DEFAULT_TIMEOUT_IN_SEC); } - public static void performADLogin(WebDriver driver, User user){ + public static void performADLogin(WebDriver driver, User user) { LOG.info("PerformADLogin"); UserInformationFields fields = new UserInformationFields(user); @@ -76,7 +77,7 @@ public static void performADLogin(WebDriver driver, User user){ driver.findElement(new By.ById(fields.getAadSignInButtonId())).click(); if (user.getFederationProvider() == FederationProvider.ADFS_2 && - !user.getLabName().equals(LabConstants.ARLINGTON_LAB_NAME)){ + !user.getLabName().equals(LabConstants.ARLINGTON_LAB_NAME)) { LOG.info("Loggin in ... ADFS-V2 - Entering the username in ADFSv2 form"); driver.findElement(new By.ById(SeleniumConstants.ADFSV2_WEB_USERNAME_INPUT_ID)). @@ -128,7 +129,7 @@ private static void checkAuthenticationCompletePage(WebDriver driver) { }); } - public static void performADFS2019Login(WebDriver driver, User user){ + public static void performADFS2019Login(WebDriver driver, User user) { LOG.info("PerformADFS2019Login"); UserInformationFields fields = new UserInformationFields(user); @@ -145,7 +146,7 @@ public static void performADFS2019Login(WebDriver driver, User user){ click(); } - public static void performLocalLogin(WebDriver driver, User user){ + public static void performLocalLogin(WebDriver driver, User user) { LOG.info("PerformLocalLogin"); driver.findElement(new By.ById(SeleniumConstants.B2C_LOCAL_ACCOUNT_ID)).click(); @@ -161,7 +162,7 @@ public static void performLocalLogin(WebDriver driver, User user){ click(); } - public static void performGoogleLogin(WebDriver driver, User user){ + public static void performGoogleLogin(WebDriver driver, User user) { LOG.info("PerformGoogleLogin"); driver.findElement(new By.ById(SeleniumConstants.GOOGLE_ACCOUNT_ID)).click(); @@ -181,7 +182,7 @@ public static void performGoogleLogin(WebDriver driver, User user){ waitForElementToBeVisibleAndEnable(driver, new By.ById(SeleniumConstants.GOOGLE_NEXT_BUTTON_ID)).click(); } - public static void performFacebookLogin(WebDriver driver, User user){ + public static void performFacebookLogin(WebDriver driver, User user) { LOG.info("PerformFacebookLogin"); driver.findElement(new By.ById(SeleniumConstants.FACEBOOK_ACCOUNT_ID)).click(); @@ -197,14 +198,14 @@ public static void performFacebookLogin(WebDriver driver, User user){ click(); } - public static void takeScreenShot(WebDriver driver){ + public static void takeScreenShot(WebDriver driver) { String file = System.getenv("BUILD_STAGINGDIRECTORY"); File destination = new File(file + "" + "/SeleniumError.png"); - File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); + File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(scrFile, destination); LOG.info("Screenshot can be found at: " + destination.getPath()); - } catch(Exception exception){ + } catch (Exception exception) { LOG.error("Error taking screenshot: " + exception.getMessage()); } } diff --git a/src/integrationtest/java/infrastructure/UserInformationFields.java b/src/integrationtest/java/infrastructure/UserInformationFields.java index aba6fc6c..048d3b28 100644 --- a/src/integrationtest/java/infrastructure/UserInformationFields.java +++ b/src/integrationtest/java/infrastructure/UserInformationFields.java @@ -14,19 +14,19 @@ class UserInformationFields { private String passwordInputId; private String passwordSigInButtonId; - UserInformationFields(User labUser){ + UserInformationFields(User labUser) { this.user = labUser; } String getPasswordInputId() { - if(Strings.isNullOrEmpty(passwordInputId)){ + if (Strings.isNullOrEmpty(passwordInputId)) { determineFieldIds(); } return passwordInputId; } String getPasswordSigInButtonId() { - if(Strings.isNullOrEmpty(passwordSigInButtonId)){ + if (Strings.isNullOrEmpty(passwordSigInButtonId)) { determineFieldIds(); } return passwordSigInButtonId; @@ -44,19 +44,18 @@ String getADFS2019UserNameInputId() { return SeleniumConstants.ADFS2019_UPN_INPUT_ID; } - private void determineFieldIds(){ - switch (user.getFederationProvider()){ + private void determineFieldIds() { + switch (user.getFederationProvider()) { case FederationProvider.ADFS_3: - case FederationProvider.ADFS_2019 : + case FederationProvider.ADFS_2019: passwordInputId = SeleniumConstants.ADFS2019_PASSWORD_ID; passwordSigInButtonId = SeleniumConstants.ADFS2019_SUBMIT_ID; break; case FederationProvider.ADFS_2: - if(LabConstants.ARLINGTON_LAB_NAME.equals(user.getLabName())){ + if (LabConstants.ARLINGTON_LAB_NAME.equals(user.getLabName())) { passwordInputId = SeleniumConstants.ADFSV2_ARLINGTON_WEB_PASSWORD_INPUT_ID; passwordSigInButtonId = SeleniumConstants.ADFSV2_ARLINGTON_WEB_SUBMIT_BUTTON_ID; - } - else { + } else { passwordInputId = SeleniumConstants.ADFSV2_WEB_PASSWORD_INPUT_ID; passwordSigInButtonId = SeleniumConstants.ADFSV2_WEB_SUBMIT_BUTTON_ID; } diff --git a/src/integrationtest/java/labapi/AppCredentialProvider.java b/src/integrationtest/java/labapi/AppCredentialProvider.java index 44fa733a..af949eec 100644 --- a/src/integrationtest/java/labapi/AppCredentialProvider.java +++ b/src/integrationtest/java/labapi/AppCredentialProvider.java @@ -15,13 +15,13 @@ public class AppCredentialProvider { private String oboAppIdURI; private String oboPassword; - public AppCredentialProvider(String azureEnvironment){ + public AppCredentialProvider(String azureEnvironment) { keyVaultSecretsProvider = new KeyVaultSecretsProvider(); labVaultClientId = keyVaultSecretsProvider.getSecret(LabConstants.APP_ID_KEY_VAULT_SECRET); labVaultPassword = keyVaultSecretsProvider.getSecret(LabConstants.APP_PASSWORD_KEY_VAULT_SECRET); - switch (azureEnvironment){ + switch (azureEnvironment) { case AzureEnvironment.AZURE: clientId = "c0485386-1e9a-4663-bc96-7ab30656de7f"; @@ -43,27 +43,27 @@ public AppCredentialProvider(String azureEnvironment){ } } - public String getAppId(){ + public String getAppId() { return clientId; } - public String getOboAppId(){ + public String getOboAppId() { return oboClientId; } - public String getOboAppIdURI(){ + public String getOboAppIdURI() { return oboAppIdURI; } - public String getOboAppPassword(){ + public String getOboAppPassword() { return oboPassword; } - public String getLabVaultAppId(){ + public String getLabVaultAppId() { return labVaultClientId; } - public String getLabVaultPassword(){ + public String getLabVaultPassword() { return labVaultPassword; } } diff --git a/src/integrationtest/java/labapi/B2CProvider.java b/src/integrationtest/java/labapi/B2CProvider.java index a03b2afc..1293734c 100644 --- a/src/integrationtest/java/labapi/B2CProvider.java +++ b/src/integrationtest/java/labapi/B2CProvider.java @@ -4,7 +4,7 @@ package labapi; public class B2CProvider { - public static final String NONE = "none"; + public static final String NONE = "none"; public static final String AMAZON = "amazon"; public static final String FACEBOOK = "facebook"; public static final String GOOGLE = "google"; diff --git a/src/integrationtest/java/labapi/HttpClientHelper.java b/src/integrationtest/java/labapi/HttpClientHelper.java index c2601030..a7c169c9 100644 --- a/src/integrationtest/java/labapi/HttpClientHelper.java +++ b/src/integrationtest/java/labapi/HttpClientHelper.java @@ -35,10 +35,10 @@ static String sendRequestToLab(URL labUrl, String accessToken) throws conn.setConnectTimeout(20000); StringBuilder content; - try(BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))){ + try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String inputLine; content = new StringBuilder(); - while((inputLine = in.readLine()) != null){ + while ((inputLine = in.readLine()) != null) { content.append(inputLine); } } @@ -58,11 +58,11 @@ private static URL buildUrl(String url, Map queryMap) throws return new URL(urlString); } - private static String encodeUTF8(String s){ + private static String encodeUTF8(String s) { try { return URLEncoder.encode(s, "UTF-8"); - } catch(UnsupportedEncodingException e) { - throw new IllegalArgumentException("Error: cannot encode query parameter " + s ); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("Error: cannot encode query parameter " + s); } } } diff --git a/src/integrationtest/java/labapi/KeyVaultSecretsProvider.java b/src/integrationtest/java/labapi/KeyVaultSecretsProvider.java index 47183087..2c70887c 100644 --- a/src/integrationtest/java/labapi/KeyVaultSecretsProvider.java +++ b/src/integrationtest/java/labapi/KeyVaultSecretsProvider.java @@ -25,14 +25,14 @@ public class KeyVaultSecretsProvider { private static String MAC_KEYSTORE = "KeychainStore"; - KeyVaultSecretsProvider(){ + KeyVaultSecretsProvider() { keyVaultClient = getAuthenticatedKeyVaultClient(); } static Map cache = new ConcurrentHashMap<>(); - String getSecret(String secretUrl){ - if(cache.containsKey(secretUrl)){ + String getSecret(String secretUrl) { + if (cache.containsKey(secretUrl)) { return cache.get(secretUrl); } String secret = keyVaultClient.getSecret(secretUrl).value(); @@ -44,16 +44,16 @@ String getSecret(String secretUrl){ private KeyVaultClient getAuthenticatedKeyVaultClient() { return new KeyVaultClient( new KeyVaultCredentials() { - @Override - public String doAuthenticate(String authorization, String resource, String scope) { - return requestAccessTokenForAutomation(); - } - }); + @Override + public String doAuthenticate(String authorization, String resource, String scope) { + return requestAccessTokenForAutomation(); + } + }); } private String requestAccessTokenForAutomation() { IAuthenticationResult result; - try{ + try { ConfidentialClientApplication cca = ConfidentialClientApplication.builder( CLIENT_ID, getClientCredentialFromKeyStore()). authority(TestConstants.MICROSOFT_AUTHORITY). @@ -64,10 +64,10 @@ CLIENT_ID, getClientCredentialFromKeyStore()). .build()). get(); - } catch(Exception e){ + } catch (Exception e) { throw new RuntimeException("Error acquiring token from Azure AD: " + e.getMessage()); } - if(result != null){ + if (result != null) { return result.accessToken(); } else { throw new NullPointerException("Authentication result is null"); @@ -81,10 +81,9 @@ private IClientCredential getClientCredentialFromKeyStore() { String os = System.getProperty("os.name"); KeyStore keystore; - if(os.toLowerCase().contains("windows")){ + if (os.toLowerCase().contains("windows")) { keystore = KeyStore.getInstance(WIN_KEYSTORE, KEYSTORE_PROVIDER); - } - else{ + } else { keystore = KeyStore.getInstance(MAC_KEYSTORE); } @@ -94,9 +93,9 @@ private IClientCredential getClientCredentialFromKeyStore() { publicCertificate = (X509Certificate) keystore.getCertificate( CERTIFICATE_ALIAS); - } catch (Exception e){ + } catch (Exception e) { throw new RuntimeException("Error getting certificate from keystore: " + e.getMessage()); } return ClientCredentialFactory.createFromCertificate(key, publicCertificate); - } + } } diff --git a/src/integrationtest/java/labapi/LabConstants.java b/src/integrationtest/java/labapi/LabConstants.java index f259833d..ba3ddf81 100644 --- a/src/integrationtest/java/labapi/LabConstants.java +++ b/src/integrationtest/java/labapi/LabConstants.java @@ -12,7 +12,7 @@ public class LabConstants { public final static String APP_ID_KEY_VAULT_SECRET = "https://msidlabs.vault.azure.net/secrets/LabVaultAppID"; public final static String APP_PASSWORD_KEY_VAULT_SECRET = "https://msidlabs.vault.azure.net/secrets/LabVaultAppSecret"; public final static String USER_MSA_USERNAME_URL = "https://msidlabs.vault.azure.net/secrets/MSA-MSIDLAB4-UserName"; - public final static String USER_MSA_PASSWORD_URL= "https://msidlabs.vault.azure.net/secrets/MSA-MSIDLAB4-Password"; + public final static String USER_MSA_PASSWORD_URL = "https://msidlabs.vault.azure.net/secrets/MSA-MSIDLAB4-Password"; public final static String OBO_APP_PASSWORD_URL = "https://msidlabs.vault.azure.net/secrets/TodoListServiceV2-OBO"; public final static String ARLINGTON_APP_ID = "cb7faed4-b8c0-49ee-b421-f5ed16894c83"; diff --git a/src/integrationtest/java/labapi/LabService.java b/src/integrationtest/java/labapi/LabService.java index 89109afe..801af14c 100644 --- a/src/integrationtest/java/labapi/LabService.java +++ b/src/integrationtest/java/labapi/LabService.java @@ -42,7 +42,7 @@ static void initLabApp() throws MalformedURLException { } static String getLabAccessToken() throws MalformedURLException, ExecutionException, InterruptedException { - if(labApp == null){ + if (labApp == null) { initLabApp(); } return labApp.acquireToken(ClientCredentialParameters @@ -51,7 +51,7 @@ static String getLabAccessToken() throws MalformedURLException, ExecutionExcepti get().accessToken(); } - User getUser(UserQueryParameters query){ + User getUser(UserQueryParameters query) { try { Map queryMap = query.parameters; String result = HttpClientHelper.sendRequestToLab( @@ -59,11 +59,10 @@ User getUser(UserQueryParameters query){ User[] users = convertJsonToObject(result, User[].class); User user = users[0]; - if(user.getUserType().equals("Guest")){ + if (user.getUserType().equals("Guest")) { String secretId = user.getHomeDomain().split("\\.")[0]; user.setPassword(getSecret(secretId)); - } - else { + } else { user.setPassword(getSecret(user.getLabName())); } if (query.parameters.containsKey(UserQueryParameters.FEDERATION_PROVIDER)) { @@ -77,7 +76,7 @@ User getUser(UserQueryParameters query){ } } - public static App getApp(String appId){ + public static App getApp(String appId) { try { String result = HttpClientHelper.sendRequestToLab( LabConstants.LAB_APP_ENDPOINT, appId, getLabAccessToken()); @@ -100,7 +99,7 @@ public static Lab getLab(String labId) { } } - public static String getSecret(String labName){ + public static String getSecret(String labName) { String result; try { Map queryMap = new HashMap<>(); diff --git a/src/integrationtest/java/labapi/LabUserProvider.java b/src/integrationtest/java/labapi/LabUserProvider.java index 3cb61dd4..d5b573b2 100644 --- a/src/integrationtest/java/labapi/LabUserProvider.java +++ b/src/integrationtest/java/labapi/LabUserProvider.java @@ -18,14 +18,14 @@ public class LabUserProvider { private final LabService labService; private Map userCache; - private LabUserProvider(){ + private LabUserProvider() { keyVaultSecretsProvider = new KeyVaultSecretsProvider(); labService = new LabService(); userCache = new HashMap<>(); } - public static synchronized LabUserProvider getInstance(){ - if(instance == null){ + public static synchronized LabUserProvider getInstance() { + if (instance == null) { instance = new LabUserProvider(); } return instance; @@ -43,24 +43,24 @@ public User getDefaultUser(String azureEnvironment) { return getLabUser(query); } - public User getFederatedAdfsUser(String federationProvider){ + public User getFederatedAdfsUser(String federationProvider) { return getFederatedAdfsUser(AzureEnvironment.AZURE, federationProvider); } - public User getFederatedAdfsUser(String azureEnvironment, String federationProvider){ + public User getFederatedAdfsUser(String azureEnvironment, String federationProvider) { UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, azureEnvironment); - query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, federationProvider); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); + query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, federationProvider); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.FEDERATED); return getLabUser(query); } - public User getOnPremAdfsUser(String federationProvider){ + public User getOnPremAdfsUser(String federationProvider) { UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.FEDERATION_PROVIDER, federationProvider); - query.parameters.put(UserQueryParameters.USER_TYPE, UserType.ON_PREM); + query.parameters.put(UserQueryParameters.USER_TYPE, UserType.ON_PREM); return getLabUser(query); } @@ -71,7 +71,7 @@ public User getB2cUser(String b2cProvider) { public User getB2cUser(String azureEnvironment, String b2cProvider) { UserQueryParameters query = new UserQueryParameters(); - query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, azureEnvironment); + query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, azureEnvironment); query.parameters.put(UserQueryParameters.USER_TYPE, UserType.B2C); query.parameters.put(UserQueryParameters.B2C_PROVIDER, b2cProvider); @@ -81,7 +81,7 @@ public User getB2cUser(String azureEnvironment, String b2cProvider) { public User getUserByAzureEnvironment(String azureEnvironment) { UserQueryParameters query = new UserQueryParameters(); - query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, azureEnvironment); + query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, azureEnvironment); return getLabUser(query); } @@ -90,16 +90,16 @@ public User getUserByGuestHomeAzureEnvironments(String guestEnvironment, String UserQueryParameters query = new UserQueryParameters(); query.parameters.put(UserQueryParameters.USER_TYPE, "guest"); - query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, guestEnvironment); - query.parameters.put(UserQueryParameters.HOME_AZURE_ENVIRONMENT, homeEnvironment); - query.parameters.put(UserQueryParameters.GUEST_HOME_DIN, "hostazuread"); - query.parameters.put(UserQueryParameters.SIGN_IN_AUDIENCE, "azureadmyorg"); + query.parameters.put(UserQueryParameters.AZURE_ENVIRONMENT, guestEnvironment); + query.parameters.put(UserQueryParameters.HOME_AZURE_ENVIRONMENT, homeEnvironment); + query.parameters.put(UserQueryParameters.GUEST_HOME_DIN, "hostazuread"); + query.parameters.put(UserQueryParameters.SIGN_IN_AUDIENCE, "azureadmyorg"); return getLabUser(query); } - public User getLabUser(UserQueryParameters userQuery){ - if(userCache.containsKey(userQuery)){ + public User getLabUser(UserQueryParameters userQuery) { + if (userCache.containsKey(userQuery)) { return userCache.get(userQuery); } User response = labService.getUser(userQuery); diff --git a/src/integrationtest/java/labapi/User.java b/src/integrationtest/java/labapi/User.java index 6fdff2db..50c2d325 100644 --- a/src/integrationtest/java/labapi/User.java +++ b/src/integrationtest/java/labapi/User.java @@ -8,8 +8,7 @@ import lombok.Setter; @Getter -public class User -{ +public class User { @JsonProperty("appId") private String appId; diff --git a/src/main/java/com/microsoft/aad/msal4j/AADAuthority.java b/src/main/java/com/microsoft/aad/msal4j/AADAuthority.java index 7febd0ef..97486fae 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AADAuthority.java +++ b/src/main/java/com/microsoft/aad/msal4j/AADAuthority.java @@ -9,7 +9,7 @@ import lombok.Getter; import lombok.experimental.Accessors; -@Accessors(fluent=true) +@Accessors(fluent = true) @Getter(AccessLevel.PACKAGE) class AADAuthority extends Authority { diff --git a/src/main/java/com/microsoft/aad/msal4j/ADFSAuthority.java b/src/main/java/com/microsoft/aad/msal4j/ADFSAuthority.java index 7b5f6574..678d602e 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ADFSAuthority.java +++ b/src/main/java/com/microsoft/aad/msal4j/ADFSAuthority.java @@ -5,7 +5,7 @@ import java.net.URL; -class ADFSAuthority extends Authority{ +class ADFSAuthority extends Authority { final static String AUTHORIZATION_ENDPOINT = "oauth2/authorize"; final static String TOKEN_ENDPOINT = "oauth2/token"; diff --git a/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java b/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java index 03bd78cb..1a8f3372 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java +++ b/src/main/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryProvider.java @@ -59,11 +59,10 @@ static InstanceDiscoveryMetadataEntry getMetadataEntry(URL authorityUrl, return cache.get(authorityUrl.getAuthority()); } - static Set getAliases(String host){ - if(cache.containsKey(host)){ + static Set getAliases(String host) { + if (cache.containsKey(host)) { return cache.get(host).aliases(); - } - else{ + } else { return Collections.singleton(host); } } @@ -76,7 +75,7 @@ static AadInstanceDiscoveryResponse parseInstanceDiscoveryMetadata(String instan instanceDiscoveryJson, AadInstanceDiscoveryResponse.class); - } catch(Exception ex){ + } catch (Exception ex) { throw new MsalClientException("Error parsing instance discovery response. Data must be " + "in valid JSON format. For more information, see https://aka.ms/msal4j-instance-discovery", AuthenticationErrorCode.INVALID_INSTANCE_DISCOVERY_METADATA); @@ -90,7 +89,7 @@ static void cacheInstanceDiscoveryMetadata(String host, if (aadInstanceDiscoveryResponse != null && aadInstanceDiscoveryResponse.metadata() != null) { for (InstanceDiscoveryMetadataEntry entry : aadInstanceDiscoveryResponse.metadata()) { - for (String alias: entry.aliases()) { + for (String alias : entry.aliases()) { cache.put(alias, entry); } } @@ -191,8 +190,7 @@ private static int determineRegionOutcome(String detectedRegion, String provided } else { regionOutcomeTelemetryValue = RegionTelemetry.REGION_OUTCOME_DEVELOPER_AUTODETECT_MISMATCH.telemetryValue; } - } - else if (autoDetect) { + } else if (autoDetect) { if (detectedRegion != null) { regionOutcomeTelemetryValue = RegionTelemetry.REGION_OUTCOME_AUTODETECT_SUCCESS.telemetryValue; } else { @@ -267,7 +265,7 @@ private static void doInstanceDiscoveryAndCache(URL authorityUrl, AadInstanceDiscoveryResponse aadInstanceDiscoveryResponse = null; - if(msalRequest.application().authenticationAuthority.authorityType.equals(AuthorityType.AAD)) { + if (msalRequest.application().authenticationAuthority.authorityType.equals(AuthorityType.AAD)) { aadInstanceDiscoveryResponse = sendInstanceDiscoveryRequest(authorityUrl, msalRequest, serviceBundle); if (validateAuthority) { diff --git a/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java b/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java index ca9780d1..30cabf91 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java +++ b/src/main/java/com/microsoft/aad/msal4j/AbstractClientApplicationBase.java @@ -632,10 +632,10 @@ public T autoDetectRegion(boolean val) { /** * Indicates that the library should attempt to fetch the instance discovery metadata from the specified Azure region. - * + *

* If the region is valid, token requests will be sent to the regional ESTS endpoint rather than the global endpoint. * If region information could not be verified, the library will fall back to using the global endpoint, which is also - * the default behavior if this value is not set. + * the default behavior if this value is not set. * * @param val boolean (default is false) * @return instance of the Builder on which method was called diff --git a/src/main/java/com/microsoft/aad/msal4j/AbstractMsalAuthorizationGrant.java b/src/main/java/com/microsoft/aad/msal4j/AbstractMsalAuthorizationGrant.java index 20ae1eac..caf116b7 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AbstractMsalAuthorizationGrant.java +++ b/src/main/java/com/microsoft/aad/msal4j/AbstractMsalAuthorizationGrant.java @@ -12,7 +12,7 @@ abstract class AbstractMsalAuthorizationGrant { /** - * Converts the grant into a HTTP parameters map. + * Converts the grant into a HTTP parameters map. * * @return A map contains the HTTP parameters */ diff --git a/src/main/java/com/microsoft/aad/msal4j/Account.java b/src/main/java/com/microsoft/aad/msal4j/Account.java index 2c222a54..926419e4 100644 --- a/src/main/java/com/microsoft/aad/msal4j/Account.java +++ b/src/main/java/com/microsoft/aad/msal4j/Account.java @@ -7,6 +7,7 @@ import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; + import java.util.Map; /** diff --git a/src/main/java/com/microsoft/aad/msal4j/AccountCacheEntity.java b/src/main/java/com/microsoft/aad/msal4j/AccountCacheEntity.java index a1e39cd3..e3ac2578 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AccountCacheEntity.java +++ b/src/main/java/com/microsoft/aad/msal4j/AccountCacheEntity.java @@ -99,11 +99,11 @@ static AccountCacheEntity createADFSAccount(Authority requestAuthority, IdToken return account; } - static AccountCacheEntity create(String clientInfoStr, Authority requestAuthority, IdToken idToken){ + static AccountCacheEntity create(String clientInfoStr, Authority requestAuthority, IdToken idToken) { return create(clientInfoStr, requestAuthority, idToken, null); } - IAccount toAccount(){ + IAccount toAccount() { return new Account(homeAccountId, environment, username, null); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java b/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java index e0a67cc5..92c33ced 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java +++ b/src/main/java/com/microsoft/aad/msal4j/AcquireTokenByDeviceCodeFlowSupplier.java @@ -11,7 +11,7 @@ class AcquireTokenByDeviceCodeFlowSupplier extends AuthenticationResultSupplier private DeviceCodeFlowRequest deviceCodeFlowRequest; - AcquireTokenByDeviceCodeFlowSupplier(PublicClientApplication clientApplication, + AcquireTokenByDeviceCodeFlowSupplier(PublicClientApplication clientApplication, DeviceCodeFlowRequest deviceCodeFlowRequest) { super(clientApplication, deviceCodeFlowRequest); this.deviceCodeFlowRequest = deviceCodeFlowRequest; @@ -68,7 +68,7 @@ private AuthenticationResult acquireTokenWithDeviceCode(DeviceCode deviceCode, throw new MsalClientException("Expired Device code", AuthenticationErrorCode.CODE_EXPIRED); } - private Long getCurrentSystemTimeInSeconds(){ + private Long getCurrentSystemTimeInSeconds() { return TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java b/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java index 6a7ff825..8a45183e 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java +++ b/src/main/java/com/microsoft/aad/msal4j/AcquireTokenSilentSupplier.java @@ -86,8 +86,7 @@ AuthenticationResult execute() throws Exception { // only because of refreshOn, then simply return the existing cached token if (afterRefreshOn && !(silentRequest.parameters().forceRefresh() || StringHelper.isBlank(res.accessToken()))) { return res; - } - else throw ex; + } else throw ex; } } else { res = null; diff --git a/src/main/java/com/microsoft/aad/msal4j/ApiEvent.java b/src/main/java/com/microsoft/aad/msal4j/ApiEvent.java index 1fab6ff7..6bc46516 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ApiEvent.java +++ b/src/main/java/com/microsoft/aad/msal4j/ApiEvent.java @@ -8,7 +8,7 @@ import static com.microsoft.aad.msal4j.TelemetryConstants.EVENT_NAME_PREFIX; -class ApiEvent extends Event{ +class ApiEvent extends Event { private static final String API_ID_KEY = EVENT_NAME_PREFIX + "api_id"; private static final String AUTHORITY_KEY = EVENT_NAME_PREFIX + "authority"; private static final String AUTHORITY_TYPE_KEY = EVENT_NAME_PREFIX + "authority_type"; @@ -22,60 +22,60 @@ class ApiEvent extends Event{ private Boolean logPii; - public ApiEvent(Boolean logPii){ + public ApiEvent(Boolean logPii) { super(TelemetryConstants.API_EVENT_NAME_KEY); this.logPii = logPii; } - public void setApiId(int apiId){ + public void setApiId(int apiId) { this.put(API_ID_KEY, Integer.toString(apiId).toLowerCase(Locale.ROOT)); } - public void setAuthority(URI authority){ + public void setAuthority(URI authority) { this.put(AUTHORITY_KEY, scrubTenant(authority)); } - public void setAuthorityType(String authorityType){ + public void setAuthorityType(String authorityType) { this.put(AUTHORITY_TYPE_KEY, authorityType.toLowerCase(Locale.ROOT)); } - public void setTenantId(String tenantId){ - if(!StringHelper.isBlank(tenantId) && logPii){ + public void setTenantId(String tenantId) { + if (!StringHelper.isBlank(tenantId) && logPii) { this.put(TENANT_ID_KEY, StringHelper.createBase64EncodedSha256Hash(tenantId)); } else { this.put(TENANT_ID_KEY, null); } } - public void setAccountId(String accountId){ - if(!StringHelper.isBlank(accountId) && logPii){ + public void setAccountId(String accountId) { + if (!StringHelper.isBlank(accountId) && logPii) { this.put(USER_ID_KEY, StringHelper.createBase64EncodedSha256Hash(accountId)); } else { this.put(USER_ID_KEY, null); } } - public void setWasSuccessful(boolean wasSuccessful){ + public void setWasSuccessful(boolean wasSuccessful) { this.put(WAS_SUCCESSFUL_KEY, String.valueOf(wasSuccessful).toLowerCase(Locale.ROOT)); } - public boolean getWasSuccessful(){ + public boolean getWasSuccessful() { return Boolean.valueOf(this.get(WAS_SUCCESSFUL_KEY)); } - public void setCorrelationId(String correlationId){ + public void setCorrelationId(String correlationId) { this.put(CORRELATION_ID_KEY, correlationId); } - public void setRequestId(String requestId){ + public void setRequestId(String requestId) { this.put(REQUEST_ID_KEY, requestId); } - public void setIsConfidentialClient(boolean isConfidentialClient){ + public void setIsConfidentialClient(boolean isConfidentialClient) { this.put(IS_CONFIDENTIAL_CLIENT_KEY, String.valueOf(isConfidentialClient).toLowerCase(Locale.ROOT)); } - public void setApiErrorCode(String apiErrorCode){ + public void setApiErrorCode(String apiErrorCode) { this.put(API_ERROR_CODE_KEY, apiErrorCode); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/AppMetadataCacheEntity.java b/src/main/java/com/microsoft/aad/msal4j/AppMetadataCacheEntity.java index 3c1eeb45..9650df09 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AppMetadataCacheEntity.java +++ b/src/main/java/com/microsoft/aad/msal4j/AppMetadataCacheEntity.java @@ -27,7 +27,7 @@ class AppMetadataCacheEntity { @JsonProperty("family_id") private String familyId; - String getKey(){ + String getKey() { List keyParts = new ArrayList<>(); keyParts.add(APP_METADATA_CACHE_ENTITY_ID); diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java b/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java index ad20bf0c..7c686ae7 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthenticationResultSupplier.java @@ -3,6 +3,7 @@ package com.microsoft.aad.msal4j; +import java.nio.charset.StandardCharsets; import java.util.Base64; import java.io.UnsupportedEncodingException; @@ -49,33 +50,33 @@ public IAuthenticationResult get() { ApiEvent apiEvent = initializeApiEvent(msalRequest); - try(TelemetryHelper telemetryHelper = - clientApplication.getServiceBundle().getTelemetryManager().createTelemetryHelper( - msalRequest.requestContext().telemetryRequestId(), - msalRequest.application().clientId(), - apiEvent, - true)) { + try (TelemetryHelper telemetryHelper = + clientApplication.getServiceBundle().getTelemetryManager().createTelemetryHelper( + msalRequest.requestContext().telemetryRequestId(), + msalRequest.application().clientId(), + apiEvent, + true)) { try { result = execute(); apiEvent.setWasSuccessful(true); - if(result != null){ + if (result != null) { logResult(result, msalRequest.headers()); if (result.account() != null) { apiEvent.setTenantId(result.accountCacheEntity().realm()); } } - } catch(Exception ex) { + } catch (Exception ex) { String error = StringHelper.EMPTY_STRING; if (ex instanceof MsalException) { MsalException exception = ((MsalException) ex); - if (exception.errorCode() != null){ + if (exception.errorCode() != null) { apiEvent.setApiErrorCode(exception.errorCode()); } } else { - if (ex.getCause() != null){ + if (ex.getCause() != null) { error = ex.getCause().toString(); } } @@ -100,26 +101,23 @@ private void logResult(AuthenticationResult result, HttpHeaders headers) { if (!StringHelper.isBlank(result.refreshToken())) { String refreshTokenHash = this.computeSha256Hash(result .refreshToken()); - if(clientApplication.logPii()){ + if (clientApplication.logPii()) { clientApplication.log.debug(LogHelper.createMessage(String.format( "Access Token with hash '%s' and Refresh Token with hash '%s' returned", accessTokenHash, refreshTokenHash), headers.getHeaderCorrelationIdValue())); - } - else{ + } else { clientApplication.log.debug( LogHelper.createMessage( "Access Token and Refresh Token were returned", headers.getHeaderCorrelationIdValue())); } - } - else { - if(clientApplication.logPii()){ + } else { + if (clientApplication.logPii()) { clientApplication.log.debug(LogHelper.createMessage(String.format( "Access Token with hash '%s' returned", accessTokenHash), headers.getHeaderCorrelationIdValue())); - } - else{ + } else { clientApplication.log.debug(LogHelper.createMessage( "Access Token was returned", headers.getHeaderCorrelationIdValue())); @@ -128,24 +126,24 @@ private void logResult(AuthenticationResult result, HttpHeaders headers) { } } - private void logException(Exception ex) { + private void logException(Exception ex) { - String logMessage = LogHelper.createMessage( - "Execution of " + this.getClass() + " failed.", - msalRequest.headers().getHeaderCorrelationIdValue()); + String logMessage = LogHelper.createMessage( + "Execution of " + this.getClass() + " failed.", + msalRequest.headers().getHeaderCorrelationIdValue()); - if (ex instanceof MsalClientException) { - MsalClientException exception = (MsalClientException) ex; - if (exception.errorCode() != null && exception.errorCode().equalsIgnoreCase(AuthenticationErrorCode.CACHE_MISS)) { - clientApplication.log.debug(logMessage, ex); - return; - } - } + if (ex instanceof MsalClientException) { + MsalClientException exception = (MsalClientException) ex; + if (exception.errorCode() != null && exception.errorCode().equalsIgnoreCase(AuthenticationErrorCode.CACHE_MISS)) { + clientApplication.log.debug(logMessage, ex); + return; + } + } - clientApplication.log.error(logMessage, ex); - } + clientApplication.log.error(logMessage, ex); + } - private ApiEvent initializeApiEvent(MsalRequest msalRequest){ + private ApiEvent initializeApiEvent(MsalRequest msalRequest) { ApiEvent apiEvent = new ApiEvent(clientApplication.logPii()); msalRequest.requestContext().telemetryRequestId( clientApplication.getServiceBundle().getTelemetryManager().generateRequestId()); @@ -154,7 +152,7 @@ private ApiEvent initializeApiEvent(MsalRequest msalRequest){ apiEvent.setRequestId(msalRequest.requestContext().telemetryRequestId()); apiEvent.setWasSuccessful(false); - if(clientApplication instanceof ConfidentialClientApplication){ + if (clientApplication instanceof ConfidentialClientApplication) { apiEvent.setIsConfidentialClient(true); } else { apiEvent.setIsConfidentialClient(false); @@ -166,7 +164,7 @@ private ApiEvent initializeApiEvent(MsalRequest msalRequest){ apiEvent.setAuthority(new URI(authenticationAuthority.authority())); apiEvent.setAuthorityType(authenticationAuthority.authorityType().toString()); } - } catch (URISyntaxException ex){ + } catch (URISyntaxException ex) { clientApplication.log.warn(LogHelper.createMessage( "Setting URL telemetry fields failed: " + LogHelper.getPiiScrubbedDetails(ex), @@ -177,13 +175,12 @@ private ApiEvent initializeApiEvent(MsalRequest msalRequest){ } private String computeSha256Hash(String input) { - try{ + try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); - digest.update(input.getBytes("UTF-8")); + digest.update(input.getBytes(StandardCharsets.UTF_8)); byte[] hash = digest.digest(); return Base64.getUrlEncoder().encodeToString(hash); - } - catch (NoSuchAlgorithmException | UnsupportedEncodingException ex){ + } catch (NoSuchAlgorithmException ex) { clientApplication.log.warn(LogHelper.createMessage( "Failed to compute SHA-256 hash due to exception - ", LogHelper.getPiiScrubbedDetails(ex))); diff --git a/src/main/java/com/microsoft/aad/msal4j/Authority.java b/src/main/java/com/microsoft/aad/msal4j/Authority.java index 8ca9c63c..c1c86d68 100644 --- a/src/main/java/com/microsoft/aad/msal4j/Authority.java +++ b/src/main/java/com/microsoft/aad/msal4j/Authority.java @@ -35,7 +35,7 @@ abstract class Authority { String authorizationEndpoint; String tokenEndpoint; - + String deviceCodeEndpoint; URL tokenEndpointUrl() throws MalformedURLException { diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeParameters.java b/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeParameters.java index b39d11f5..1b69e40a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeParameters.java @@ -64,8 +64,9 @@ private static AuthorizationCodeParametersBuilder builder() { /** * Builder for {@link AuthorizationCodeParameters} + * * @param authorizationCode code received from the service authorization endpoint - * @param redirectUri URI where authorization code was received + * @param redirectUri URI where authorization code was received * @return builder object that can be used to construct {@link AuthorizationCodeParameters} */ public static AuthorizationCodeParametersBuilder builder(String authorizationCode, URI redirectUri) { diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeRequest.java b/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeRequest.java index d4236e30..e199b20a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthorizationCodeRequest.java @@ -12,14 +12,14 @@ class AuthorizationCodeRequest extends MsalRequest { AuthorizationCodeRequest(AuthorizationCodeParameters parameters, AbstractClientApplicationBase application, - RequestContext requestContext){ + RequestContext requestContext) { super(application, createMsalGrant(parameters), requestContext); } - private static AbstractMsalAuthorizationGrant createMsalGrant(AuthorizationCodeParameters parameters){ + private static AbstractMsalAuthorizationGrant createMsalGrant(AuthorizationCodeParameters parameters) { AuthorizationGrant authorizationGrant; - if(parameters.codeVerifier() != null){ + if (parameters.codeVerifier() != null) { authorizationGrant = new AuthorizationCodeGrant( new AuthorizationCode(parameters.authorizationCode()), parameters.redirectUri(), @@ -27,7 +27,7 @@ private static AbstractMsalAuthorizationGrant createMsalGrant(AuthorizationCodeP } else { authorizationGrant = new AuthorizationCodeGrant( - new AuthorizationCode(parameters.authorizationCode()),parameters.redirectUri()); + new AuthorizationCode(parameters.authorizationCode()), parameters.redirectUri()); } return new OAuthAuthorizationGrant(authorizationGrant, parameters.scopes(), parameters.claims()); diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParameters.java b/src/main/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParameters.java index 87b4b40b..2b55db8b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParameters.java @@ -34,7 +34,7 @@ public class AuthorizationRequestUrlParameters { private String correlationId; private boolean instanceAware; - Map> requestParameters = new HashMap<>(); + Map> requestParameters = new HashMap<>(); public static Builder builder(String redirectUri, Set scopes) { @@ -51,7 +51,7 @@ private static Builder builder() { return new Builder(); } - private AuthorizationRequestUrlParameters(Builder builder){ + private AuthorizationRequestUrlParameters(Builder builder) { //required parameters this.redirectUri = builder.redirectUri; requestParameters.put("redirect_uri", Collections.singletonList(this.redirectUri)); @@ -63,26 +63,26 @@ private AuthorizationRequestUrlParameters(Builder builder){ scopesParam.addAll(builder.scopes); - if(builder.extraScopesToConsent != null) { + if (builder.extraScopesToConsent != null) { scopesParam.addAll(builder.extraScopesToConsent); } this.scopes = scopesParam; requestParameters.put("scope", Collections.singletonList(String.join(" ", scopesParam))); - requestParameters.put("response_type",Collections.singletonList("code")); + requestParameters.put("response_type", Collections.singletonList("code")); // Optional parameters - if(builder.claims != null) { + if (builder.claims != null) { String claimsParam = String.join(" ", builder.claims); requestParameters.put("claims", Collections.singletonList(claimsParam)); } - if(builder.claimsChallenge != null && builder.claimsChallenge.trim().length() > 0){ + if (builder.claimsChallenge != null && builder.claimsChallenge.trim().length() > 0) { JsonHelper.validateJsonFormat(builder.claimsChallenge); requestParameters.put("claims", Collections.singletonList(builder.claimsChallenge)); } - if(builder.claimsRequest != null){ + if (builder.claimsRequest != null) { String claimsRequest = builder.claimsRequest.formatAsJSONString(); //If there are other claims (such as part of a claims challenge), merge them with this claims request. if (requestParameters.get("claims") != null) { @@ -91,27 +91,27 @@ private AuthorizationRequestUrlParameters(Builder builder){ requestParameters.put("claims", Collections.singletonList(claimsRequest)); } - if(builder.codeChallenge != null){ + if (builder.codeChallenge != null) { this.codeChallenge = builder.codeChallenge; requestParameters.put("code_challenge", Collections.singletonList(builder.codeChallenge)); } - if(builder.codeChallengeMethod != null){ + if (builder.codeChallengeMethod != null) { this.codeChallengeMethod = builder.codeChallengeMethod; requestParameters.put("code_challenge_method", Collections.singletonList(builder.codeChallengeMethod)); } - if(builder.state != null){ + if (builder.state != null) { this.state = builder.state; requestParameters.put("state", Collections.singletonList(builder.state)); } - if(builder.nonce != null){ + if (builder.nonce != null) { this.nonce = builder.nonce; requestParameters.put("nonce", Collections.singletonList(builder.nonce)); } - if(builder.responseMode != null){ + if (builder.responseMode != null) { this.responseMode = builder.responseMode; requestParameters.put("response_mode", Collections.singletonList( builder.responseMode.toString())); @@ -121,7 +121,7 @@ private AuthorizationRequestUrlParameters(Builder builder){ ResponseMode.FORM_POST.toString())); } - if(builder.loginHint != null){ + if (builder.loginHint != null) { this.loginHint = loginHint(); requestParameters.put("login_hint", Collections.singletonList(builder.loginHint)); @@ -130,29 +130,29 @@ private AuthorizationRequestUrlParameters(Builder builder){ String.format(HttpHeaders.X_ANCHOR_MAILBOX_UPN_FORMAT, builder.loginHint))); } - if(builder.domainHint != null){ + if (builder.domainHint != null) { this.domainHint = domainHint(); requestParameters.put("domain_hint", Collections.singletonList(builder.domainHint)); } - if(builder.prompt != null){ + if (builder.prompt != null) { this.prompt = builder.prompt; requestParameters.put("prompt", Collections.singletonList(builder.prompt.toString())); } - if(builder.correlationId != null){ + if (builder.correlationId != null) { this.correlationId = builder.correlationId; requestParameters.put("correlation_id", Collections.singletonList(builder.correlationId)); } - if(builder.instanceAware){ + if (builder.instanceAware) { this.instanceAware = builder.instanceAware; requestParameters.put("instance_aware", Collections.singletonList(String.valueOf(instanceAware))); } } URL createAuthorizationURL(Authority authority, - Map> requestParameters){ + Map> requestParameters) { URL authorizationRequestUrl; try { String authorizationCodeEndpoint = authority.authorizationEndpoint(); @@ -160,7 +160,7 @@ URL createAuthorizationURL(Authority authority, URLUtils.serializeParameters(requestParameters); authorizationRequestUrl = new URL(uriString); - } catch(MalformedURLException ex){ + } catch (MalformedURLException ex) { throw new MsalClientException(ex); } return authorizationRequestUrl; @@ -185,7 +185,7 @@ public static class Builder { private String correlationId; private boolean instanceAware; - public AuthorizationRequestUrlParameters build(){ + public AuthorizationRequestUrlParameters build() { return new AuthorizationRequestUrlParameters(this); } @@ -197,7 +197,7 @@ private Builder self() { * The redirect URI where authentication responses can be received by your application. It * must exactly match one of the redirect URIs registered in the Azure portal. */ - public Builder redirectUri(String val){ + public Builder redirectUri(String val) { this.redirectUri = val; return self(); } @@ -205,7 +205,7 @@ public Builder redirectUri(String val){ /** * Scopes which the application is requesting access to and the user will consent to. */ - public Builder scopes(Set val){ + public Builder scopes(Set val) { this.scopes = val; return self(); } @@ -214,7 +214,7 @@ public Builder scopes(Set val){ * Scopes that you can request the end user to consent upfront, * in addition to scopes which the application is requesting access to. */ - public Builder extraScopesToConsent(Set val){ + public Builder extraScopesToConsent(Set val) { this.extraScopesToConsent = val; return self(); } @@ -224,7 +224,7 @@ public Builder extraScopesToConsent(Set val){ * policy has not been met,{@link MsalServiceException} will contain claims that need be * consented to. */ - public Builder claimsChallenge(String val){ + public Builder claimsChallenge(String val) { this.claimsChallenge = val; return self(); } @@ -232,7 +232,7 @@ public Builder claimsChallenge(String val){ /** * Claims to be requested through the OIDC claims request parameter, allowing requests for standard and custom claims */ - public Builder claims(ClaimsRequest val){ + public Builder claims(ClaimsRequest val) { this.claimsRequest = val; return self(); } @@ -242,7 +242,7 @@ public Builder claims(ClaimsRequest val){ * Required if codeChallenge is included. For more information, see the PKCE RCF: * https://tools.ietf.org/html/rfc7636 */ - public Builder codeChallenge(String val){ + public Builder codeChallenge(String val) { this.codeChallenge = val; return self(); } @@ -252,7 +252,7 @@ public Builder codeChallenge(String val){ * of plain or S256. If excluded, code challenge is assumed to be plaintext. For more * information, see the PKCE RCF: https://tools.ietf.org/html/rfc7636 */ - public Builder codeChallengeMethod(String val){ + public Builder codeChallengeMethod(String val) { this.codeChallengeMethod = val; return self(); } @@ -262,17 +262,17 @@ public Builder codeChallengeMethod(String val){ * generated unique value is typically used for preventing cross site request forgery attacks. * The state is also used to encode information about the user's state in the app before the * authentication request occurred. - * */ - public Builder state(String val){ + */ + public Builder state(String val) { this.state = val; return self(); } /** - * A value included in the request that is also returned in the token response. A randomly - * generated unique value is typically used for preventing cross site request forgery attacks. + * A value included in the request that is also returned in the token response. A randomly + * generated unique value is typically used for preventing cross site request forgery attacks. */ - public Builder nonce(String val){ + public Builder nonce(String val) { this.nonce = val; return self(); } @@ -280,7 +280,7 @@ public Builder nonce(String val){ /** * Specifies the method that should be used to send the authentication result to your app. */ - public Builder responseMode(ResponseMode val){ + public Builder responseMode(ResponseMode val) { this.responseMode = val; return self(); } @@ -291,7 +291,7 @@ public Builder responseMode(ResponseMode val){ * re-authentication, having already extracted the username from a previous sign-in using the * preferred_username claim. */ - public Builder loginHint(String val){ + public Builder loginHint(String val) { this.loginHint = val; return self(); } @@ -300,7 +300,7 @@ public Builder loginHint(String val){ * Provides a hint about the tenant or domain that the user should use to sign in. The value * of the domain hint is a registered domain for the tenant. **/ - public Builder domainHint(String val){ + public Builder domainHint(String val) { this.domainHint = val; return self(); } @@ -309,7 +309,7 @@ public Builder domainHint(String val){ * Indicates the type of user interaction that is required. Possible values are * {@link Prompt} */ - public Builder prompt(Prompt val){ + public Builder prompt(Prompt val) { this.prompt = val; return self(); } @@ -317,7 +317,7 @@ public Builder prompt(Prompt val){ /** * Identifier used to correlate requests for telemetry purposes. Usually a GUID. */ - public Builder correlationId(String val){ + public Builder correlationId(String val) { this.correlationId = val; return self(); } @@ -326,7 +326,7 @@ public Builder correlationId(String val){ * If set to true, the authorization result will contain the authority for the user's home cloud, and this authority * will be used for the token request instead of the authority set in the application. */ - public Builder instanceAware(boolean val){ + public Builder instanceAware(boolean val) { this.instanceAware = val; return self(); } diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthorizationResponseHandler.java b/src/main/java/com/microsoft/aad/msal4j/AuthorizationResponseHandler.java index c1bfdad0..242e0d83 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthorizationResponseHandler.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthorizationResponseHandler.java @@ -24,9 +24,9 @@ class AuthorizationResponseHandler implements HttpHandler { private final static Logger LOG = LoggerFactory.getLogger(AuthorizationResponseHandler.class); - private final static String DEFAULT_SUCCESS_MESSAGE = "Authentication Complete"+ - " Authentication complete. You can close the browser and return to the application."+ - " " ; + private final static String DEFAULT_SUCCESS_MESSAGE = "Authentication Complete" + + " Authentication complete. You can close the browser and return to the application." + + " "; private final static String DEFAULT_FAILURE_MESSAGE = "Authentication Failed " + " Authentication failed. You can return to the application. Feel free to close this browser tab. " + @@ -36,15 +36,15 @@ class AuthorizationResponseHandler implements HttpHandler { private SystemBrowserOptions systemBrowserOptions; AuthorizationResponseHandler(BlockingQueue authorizationResultQueue, - SystemBrowserOptions systemBrowserOptions){ + SystemBrowserOptions systemBrowserOptions) { this.authorizationResultQueue = authorizationResultQueue; this.systemBrowserOptions = systemBrowserOptions; } @Override public void handle(HttpExchange httpExchange) throws IOException { - try{ - if(!httpExchange.getRequestURI().getPath().equalsIgnoreCase("/")){ + try { + if (!httpExchange.getRequestURI().getPath().equalsIgnoreCase("/")) { httpExchange.sendResponseHeaders(200, 0); return; } @@ -54,8 +54,8 @@ public void handle(HttpExchange httpExchange) throws IOException { AuthorizationResult result = AuthorizationResult.fromResponseBody(responseBody); sendResponse(httpExchange, result); authorizationResultQueue.put(result); - - } catch (InterruptedException ex){ + + } catch (InterruptedException ex) { LOG.error("Error reading response from socket: " + ex.getMessage()); throw new MsalClientException(ex); } finally { @@ -64,9 +64,9 @@ public void handle(HttpExchange httpExchange) throws IOException { } private void sendResponse(HttpExchange httpExchange, AuthorizationResult result) - throws IOException{ + throws IOException { - switch (result.status()){ + switch (result.status()) { case Success: sendSuccessResponse(httpExchange, getSuccessfulResponseMessage()); break; @@ -86,35 +86,35 @@ private void sendSuccessResponse(HttpExchange httpExchange, String response) thr } private void sendErrorResponse(HttpExchange httpExchange, String response) throws IOException { - if(systemBrowserOptions == null || systemBrowserOptions.browserRedirectError() == null){ + if (systemBrowserOptions == null || systemBrowserOptions.browserRedirectError() == null) { send200Response(httpExchange, response); } else { send302Response(httpExchange, systemBrowserOptions().browserRedirectError().toString()); } } - private void send302Response(HttpExchange httpExchange, String redirectUri) throws IOException{ + private void send302Response(HttpExchange httpExchange, String redirectUri) throws IOException { Headers responseHeaders = httpExchange.getResponseHeaders(); responseHeaders.set("Location", redirectUri); httpExchange.sendResponseHeaders(302, 0); } - private void send200Response(HttpExchange httpExchange, String response) throws IOException{ + private void send200Response(HttpExchange httpExchange, String response) throws IOException { httpExchange.sendResponseHeaders(200, response.length()); OutputStream os = httpExchange.getResponseBody(); os.write(response.getBytes()); os.close(); } - private String getSuccessfulResponseMessage(){ - if(systemBrowserOptions == null || systemBrowserOptions.htmlMessageSuccess() == null) { + private String getSuccessfulResponseMessage() { + if (systemBrowserOptions == null || systemBrowserOptions.htmlMessageSuccess() == null) { return DEFAULT_SUCCESS_MESSAGE; } return systemBrowserOptions().htmlMessageSuccess(); } - private String getErrorResponseMessage(){ - if(systemBrowserOptions == null || systemBrowserOptions.htmlMessageError() == null) { + private String getErrorResponseMessage() { + if (systemBrowserOptions == null || systemBrowserOptions.htmlMessageError() == null) { return DEFAULT_FAILURE_MESSAGE; } return systemBrowserOptions().htmlMessageSuccess(); diff --git a/src/main/java/com/microsoft/aad/msal4j/AuthorizationResult.java b/src/main/java/com/microsoft/aad/msal4j/AuthorizationResult.java index 9ef1bbe5..fef3622b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AuthorizationResult.java +++ b/src/main/java/com/microsoft/aad/msal4j/AuthorizationResult.java @@ -29,9 +29,9 @@ enum AuthorizationStatus { UnknownError } - static AuthorizationResult fromResponseBody(String responseBody){ + static AuthorizationResult fromResponseBody(String responseBody) { - if(StringHelper.isBlank(responseBody)){ + if (StringHelper.isBlank(responseBody)) { return new AuthorizationResult( AuthorizationStatus.UnknownError, AuthenticationErrorCode.INVALID_AUTHORIZATION_RESULT, @@ -39,9 +39,9 @@ static AuthorizationResult fromResponseBody(String responseBody){ "is null or empty"); } - Map queryParameters = parseParameters(responseBody); + Map queryParameters = parseParameters(responseBody); - if(queryParameters.containsKey("error")){ + if (queryParameters.containsKey("error")) { return new AuthorizationResult( AuthorizationStatus.ProtocolError, queryParameters.get("error"), @@ -50,7 +50,7 @@ static AuthorizationResult fromResponseBody(String responseBody){ null); } - if(!queryParameters.containsKey("code")){ + if (!queryParameters.containsKey("code")) { return new AuthorizationResult( AuthorizationStatus.UnknownError, AuthenticationErrorCode.INVALID_AUTHORIZATION_RESULT, @@ -64,17 +64,17 @@ static AuthorizationResult fromResponseBody(String responseBody){ result.environment = queryParameters.get("cloud_instance_host_name"); } - if(queryParameters.containsKey("state")){ + if (queryParameters.containsKey("state")) { result.state = queryParameters.get("state"); } return result; } - private AuthorizationResult(){ + private AuthorizationResult() { } - private AuthorizationResult(AuthorizationStatus status, String error, String errorDescription){ + private AuthorizationResult(AuthorizationStatus status, String error, String errorDescription) { this.status = status; this.error = error; this.errorDescription = errorDescription; @@ -90,7 +90,7 @@ private static Map parseParameters(String serverResponse) { String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8"); query_pairs.put(key, value); } - } catch(Exception ex){ + } catch (Exception ex) { throw new MsalClientException( AuthenticationErrorCode.INVALID_AUTHORIZATION_RESULT, String.format("Error parsing authorization result: %s", ex.getMessage())); diff --git a/src/main/java/com/microsoft/aad/msal4j/AzureCloudEndpoint.java b/src/main/java/com/microsoft/aad/msal4j/AzureCloudEndpoint.java index dbbb5321..5eaa9ec8 100644 --- a/src/main/java/com/microsoft/aad/msal4j/AzureCloudEndpoint.java +++ b/src/main/java/com/microsoft/aad/msal4j/AzureCloudEndpoint.java @@ -6,7 +6,7 @@ /** * All the national clouds authenticate users separately in each environment and have separate authentication endpoints. * AzureCloudEndpoint is an utility enum containing URLs for each of the national clouds endpoints, as well as the public cloud endpoint - * + *

* For more details see: https://aka.ms/msal4j-national-cloud */ public enum AzureCloudEndpoint { diff --git a/src/main/java/com/microsoft/aad/msal4j/B2CAuthority.java b/src/main/java/com/microsoft/aad/msal4j/B2CAuthority.java index f5ee5605..bc94f7bf 100644 --- a/src/main/java/com/microsoft/aad/msal4j/B2CAuthority.java +++ b/src/main/java/com/microsoft/aad/msal4j/B2CAuthority.java @@ -9,9 +9,9 @@ import java.net.URL; -@Accessors(fluent=true) +@Accessors(fluent = true) @Getter(AccessLevel.PACKAGE) -class B2CAuthority extends Authority{ +class B2CAuthority extends Authority { private final static String AUTHORIZATION_ENDPOINT = "/oauth2/v2.0/authorize"; private final static String TOKEN_ENDPOINT = "/oauth2/v2.0/token"; @@ -20,13 +20,13 @@ class B2CAuthority extends Authority{ private final static String B2C_TOKEN_ENDPOINT_FORMAT = "https://%s/%s" + TOKEN_ENDPOINT + "?p=%s"; private String policy; - B2CAuthority(final URL authorityUrl){ + B2CAuthority(final URL authorityUrl) { super(authorityUrl, AuthorityType.B2C); setAuthorityProperties(); } - private void validatePathSegments(String[] segments){ - if(segments.length < 3){ + private void validatePathSegments(String[] segments) { + if (segments.length < 3) { throw new IllegalArgumentException( "B2C 'authority' Uri should have at least 3 segments in the path " + "(i.e. https:///tfp///...)"); diff --git a/src/main/java/com/microsoft/aad/msal4j/CacheTelemetry.java b/src/main/java/com/microsoft/aad/msal4j/CacheTelemetry.java index 8e7b5174..98d17b8b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/CacheTelemetry.java +++ b/src/main/java/com/microsoft/aad/msal4j/CacheTelemetry.java @@ -20,7 +20,7 @@ enum CacheTelemetry { final int telemetryValue; - CacheTelemetry(int telemetryValue){ + CacheTelemetry(int telemetryValue) { this.telemetryValue = telemetryValue; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/ClaimsRequest.java b/src/main/java/com/microsoft/aad/msal4j/ClaimsRequest.java index 05ce47b2..833bd882 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClaimsRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClaimsRequest.java @@ -34,7 +34,7 @@ public class ClaimsRequest { /** * Inserts a claim into the list of claims to be added to the "id_token" section of an OIDC claims request * - * @param claim the name of the claim to be requested + * @param claim the name of the claim to be requested * @param requestedClaimAdditionalInfo additional information about the claim being requested */ public void requestClaimInIdToken(String claim, RequestedClaimAdditionalInfo requestedClaimAdditionalInfo) { @@ -42,10 +42,9 @@ public void requestClaimInIdToken(String claim, RequestedClaimAdditionalInfo req } /** - * Inserts a claim into the list of claims to be added to the "userinfo" section of an OIDC claims request * - * @param claim the name of the claim to be requested + * @param claim the name of the claim to be requested * @param requestedClaimAdditionalInfo additional information about the claim being requested */ protected void requestClaimInUserInfo(String claim, RequestedClaimAdditionalInfo requestedClaimAdditionalInfo) { @@ -55,7 +54,7 @@ protected void requestClaimInUserInfo(String claim, RequestedClaimAdditionalInfo /** * Inserts a claim into the list of claims to be added to the "access_token" section of an OIDC claims request * - * @param claim the name of the claim to be requested + * @param claim the name of the claim to be requested * @param requestedClaimAdditionalInfo additional information about the claim being requested */ protected void requestClaimInAccessToken(String claim, RequestedClaimAdditionalInfo requestedClaimAdditionalInfo) { @@ -106,7 +105,8 @@ public static ClaimsRequest formatAsClaimsRequest(String claims) { ClaimsRequest cr = new ClaimsRequest(); ObjectMapper mapper = new ObjectMapper(); - ObjectReader reader = mapper.readerFor(new TypeReference>() {}); + ObjectReader reader = mapper.readerFor(new TypeReference>() { + }); JsonNode jsonClaims = mapper.readTree(claims); diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientAuthenticationPost.java b/src/main/java/com/microsoft/aad/msal4j/ClientAuthenticationPost.java index d0567417..322c112b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientAuthenticationPost.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientAuthenticationPost.java @@ -18,7 +18,7 @@ class ClientAuthenticationPost extends ClientAuthentication { protected ClientAuthenticationPost(ClientAuthenticationMethod method, - ClientID clientID) { + ClientID clientID) { super(method, clientID); } @@ -45,7 +45,7 @@ public void applyTo(HTTPRequest httpRequest) throws SerializeException { if (!ct.equals(HTTPContentType.ApplicationURLEncoded.contentType)) throw new SerializeException( "The HTTP Content-Type header must be " - + HTTPContentType.ApplicationURLEncoded.contentType); + + HTTPContentType.ApplicationURLEncoded.contentType); Map> params = httpRequest.getQueryParameters(); diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientCertificate.java b/src/main/java/com/microsoft/aad/msal4j/ClientCertificate.java index f17143b9..536b9765 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientCertificate.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientCertificate.java @@ -74,7 +74,7 @@ public String publicCertificateHash() throws CertificateEncodingException, NoSuchAlgorithmException { return Base64.getEncoder().encodeToString(ClientCertificate - .getHash(publicKeyCertificateChain.get(0).getEncoded())); + .getHash(publicKeyCertificateChain.get(0).getEncoded())); } public List getEncodedPublicKeyCertificateChain() throws CertificateEncodingException { @@ -90,7 +90,7 @@ static ClientCertificate create(InputStream pkcs12Certificate, String password) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { // treat null password as default one - empty string - if(password == null){ + if (password == null) { password = DEFAULT_PKCS12_PASSWORD; } @@ -106,7 +106,7 @@ static ClientCertificate create(InputStream pkcs12Certificate, String password) throw new IllegalArgumentException("more than one certificate alias found in input stream"); } - ArrayList publicKeyCertificateChain = new ArrayList<>();; + ArrayList publicKeyCertificateChain = new ArrayList<>(); PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, password.toCharArray()); X509Certificate publicKeyCertificate = (X509Certificate) keystore.getCertificate(alias); @@ -116,8 +116,7 @@ static ClientCertificate create(InputStream pkcs12Certificate, String password) for (Certificate c : chain) { publicKeyCertificateChain.add((X509Certificate) c); } - } - else{ + } else { publicKeyCertificateChain.add(publicKeyCertificate); } diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialFactory.java b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialFactory.java index cfafa00e..ab7eafef 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialFactory.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialFactory.java @@ -20,17 +20,19 @@ public class ClientCredentialFactory { /** * Static method to create a {@link ClientSecret} instance from a client secret + * * @param secret secret of application requesting a token * @return {@link ClientSecret} */ - public static IClientSecret createFromSecret(String secret){ + public static IClientSecret createFromSecret(String secret) { return new ClientSecret(secret); } /** * Static method to create a {@link ClientCertificate} instance from a certificate + * * @param pkcs12Certificate InputStream containing PCKS12 formatted certificate - * @param password certificate password + * @param password certificate password * @return {@link ClientCertificate} * @throws CertificateException * @throws UnrecoverableKeyException @@ -47,7 +49,8 @@ public static IClientCertificate createFromCertificate(final InputStream pkcs12C /** * Static method to create a {@link ClientCertificate} instance. - * @param key RSA private key to sign the assertion. + * + * @param key RSA private key to sign the assertion. * @param publicKeyCertificate x509 public certificate used for thumbprint * @return {@link ClientCertificate} */ @@ -59,12 +62,13 @@ public static IClientCertificate createFromCertificate(final PrivateKey key, fin /** * Static method to create a {@link ClientCertificate} instance. - * @param key RSA private key to sign the assertion. + * + * @param key RSA private key to sign the assertion. * @param publicKeyCertificateChain ordered with the user's certificate first followed by zero or more certificate authorities * @return {@link ClientCertificate} */ public static IClientCertificate createFromCertificateChain(PrivateKey key, List publicKeyCertificateChain) { - if(key == null || publicKeyCertificateChain == null || publicKeyCertificateChain.size() == 0){ + if (key == null || publicKeyCertificateChain == null || publicKeyCertificateChain.size() == 0) { throw new IllegalArgumentException("null or empty input parameter"); } return new ClientCertificate(key, publicKeyCertificateChain); @@ -72,10 +76,11 @@ public static IClientCertificate createFromCertificateChain(PrivateKey key, List /** * Static method to create a {@link ClientAssertion} instance. + * * @param clientAssertion Jwt token encoded as a base64 URL encoded string * @return {@link ClientAssertion} */ - public static IClientAssertion createFromClientAssertion(String clientAssertion){ + public static IClientAssertion createFromClientAssertion(String clientAssertion) { return new ClientAssertion(clientAssertion); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialParameters.java b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialParameters.java index 8083e925..812c5291 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialParameters.java @@ -51,6 +51,7 @@ private static ClientCredentialParametersBuilder builder() { /** * Builder for {@link ClientCredentialParameters} + * * @param scopes scopes application is requesting access to * @return builder that can be used to construct ClientCredentialParameters */ diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialRequest.java b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialRequest.java index b9753305..164e7f87 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientCredentialRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientCredentialRequest.java @@ -5,18 +5,18 @@ import com.nimbusds.oauth2.sdk.ClientCredentialsGrant; -class ClientCredentialRequest extends MsalRequest{ +class ClientCredentialRequest extends MsalRequest { ClientCredentialParameters parameters; ClientCredentialRequest(ClientCredentialParameters parameters, ConfidentialClientApplication application, - RequestContext requestContext){ + RequestContext requestContext) { super(application, createMsalGrant(parameters), requestContext); this.parameters = parameters; } - private static OAuthAuthorizationGrant createMsalGrant(ClientCredentialParameters parameters){ + private static OAuthAuthorizationGrant createMsalGrant(ClientCredentialParameters parameters) { return new OAuthAuthorizationGrant(new ClientCredentialsGrant(), parameters.scopes(), parameters.claims()); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientInfo.java b/src/main/java/com/microsoft/aad/msal4j/ClientInfo.java index 93da1a7b..9f103d54 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientInfo.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientInfo.java @@ -21,8 +21,8 @@ class ClientInfo { @JsonProperty("utid") private String uniqueTenantIdentifier; - public static ClientInfo createFromJson(String clientInfoJsonBase64Encoded){ - if(StringHelper.isBlank(clientInfoJsonBase64Encoded)){ + public static ClientInfo createFromJson(String clientInfoJsonBase64Encoded) { + if (StringHelper.isBlank(clientInfoJsonBase64Encoded)) { return null; } @@ -31,7 +31,7 @@ public static ClientInfo createFromJson(String clientInfoJsonBase64Encoded){ return JsonHelper.convertJsonToObject(new String(decodedInput, StandardCharset.UTF_8), ClientInfo.class); } - String toAccountIdentifier(){ + String toAccountIdentifier() { return uniqueIdentifier + POINT_DELIMITER + uniqueTenantIdentifier; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/ClientSecret.java b/src/main/java/com/microsoft/aad/msal4j/ClientSecret.java index 317289c1..99f714bc 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ClientSecret.java +++ b/src/main/java/com/microsoft/aad/msal4j/ClientSecret.java @@ -14,11 +14,10 @@ final class ClientSecret implements IClientSecret { @Getter private final String clientSecret; - /** + /** * Constructor to create credential with client id and secret * - * @param clientSecret - * Secret of the client requesting the token. + * @param clientSecret Secret of the client requesting the token. */ ClientSecret(final String clientSecret) { if (StringHelper.isBlank(clientSecret)) { diff --git a/src/main/java/com/microsoft/aad/msal4j/CurrentRequest.java b/src/main/java/com/microsoft/aad/msal4j/CurrentRequest.java index e51f4d10..3a65580c 100644 --- a/src/main/java/com/microsoft/aad/msal4j/CurrentRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/CurrentRequest.java @@ -25,7 +25,7 @@ class CurrentRequest { @Setter private int regionOutcome = 0; - CurrentRequest(PublicApi publicApi){ + CurrentRequest(PublicApi publicApi) { this.publicApi = publicApi; } } \ No newline at end of file diff --git a/src/main/java/com/microsoft/aad/msal4j/DefaultEvent.java b/src/main/java/com/microsoft/aad/msal4j/DefaultEvent.java index 075b9e33..73ee5070 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DefaultEvent.java +++ b/src/main/java/com/microsoft/aad/msal4j/DefaultEvent.java @@ -14,7 +14,7 @@ class DefaultEvent extends Event { private final static String CACHE_EVENT_COUNT_KEY = TelemetryConstants.EVENT_NAME_PREFIX + "cache_event_count"; private Map eventCount; - public DefaultEvent(String clientId, Map eventCount){ + public DefaultEvent(String clientId, Map eventCount) { super(TelemetryConstants.DEFAULT_EVENT_NAME_KEY); setClientId(clientId); setSdkPlatform(); @@ -25,27 +25,27 @@ public DefaultEvent(String clientId, Map eventCount){ setCacheEventCount(); } - private void setClientId(String clientId){ + private void setClientId(String clientId) { this.put(CLIENT_ID_KEY, clientId); } - private void setSdkPlatform(){ + private void setSdkPlatform() { this.put(SDK_PLATFORM_KEY, System.getProperty("os.name")); } - private void setSdkVersion(){ + private void setSdkVersion() { this.put(SDK_VERSION_KEY, this.getClass().getPackage().getImplementationVersion()); } - private void setHttpEventCount(){ + private void setHttpEventCount() { this.put(HTTP_EVENT_COUNT_KEY, getEventCount(TelemetryConstants.HTTP_EVENT_NAME_KEY)); } - private void setCacheEventCount(){ + private void setCacheEventCount() { this.put(CACHE_EVENT_COUNT_KEY, getEventCount(TelemetryConstants.CACHE_EVENT_NAME_KEY)); } - private String getEventCount(String eventName){ + private String getEventCount(String eventName) { return eventCount.getOrDefault(eventName, 0).toString(); } diff --git a/src/main/java/com/microsoft/aad/msal4j/DefaultHttpClient.java b/src/main/java/com/microsoft/aad/msal4j/DefaultHttpClient.java index 025c673e..a563b369 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DefaultHttpClient.java +++ b/src/main/java/com/microsoft/aad/msal4j/DefaultHttpClient.java @@ -17,18 +17,18 @@ class DefaultHttpClient implements IHttpClient { private final SSLSocketFactory sslSocketFactory; public int DEFAULT_CONNECT_TIMEOUT = 10000; public int DEFAULT_READ_TIMEOUT = 15000; - + private int connectTimeout = DEFAULT_CONNECT_TIMEOUT; private int readTimeout = DEFAULT_READ_TIMEOUT; - DefaultHttpClient(Proxy proxy, SSLSocketFactory sslSocketFactory, Integer connectTimeout, Integer readTimeout){ + DefaultHttpClient(Proxy proxy, SSLSocketFactory sslSocketFactory, Integer connectTimeout, Integer readTimeout) { this.proxy = proxy; this.sslSocketFactory = sslSocketFactory; if (connectTimeout != null) this.connectTimeout = connectTimeout; if (readTimeout != null) this.readTimeout = readTimeout; } - public IHttpResponse send(HttpRequest httpRequest) throws Exception{ + public IHttpResponse send(HttpRequest httpRequest) throws Exception { HttpResponse response = null; if (httpRequest.httpMethod() == HttpMethod.GET) { @@ -61,8 +61,7 @@ private HttpResponse executeHttpPost(HttpRequest httpRequest) throws Exception { wr.flush(); return readResponseFromConnection(conn); - } - finally { + } finally { if (wr != null) { wr.close(); } @@ -74,8 +73,7 @@ private HttpsURLConnection openConnection(final URL finalURL) HttpsURLConnection connection; if (proxy != null) { connection = (HttpsURLConnection) finalURL.openConnection(proxy); - } - else { + } else { connection = (HttpsURLConnection) finalURL.openConnection(); } @@ -119,9 +117,8 @@ private HttpResponse readResponseFromConnection(final HttpsURLConnection conn) t httpResponse.addHeaders(conn.getHeaderFields()); httpResponse.body(inputStreamToString(is)); return httpResponse; - } - finally { - if(is != null){ + } finally { + if (is != null) { is.close(); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/DeviceCode.java b/src/main/java/com/microsoft/aad/msal4j/DeviceCode.java index 8af17104..cd261dbc 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DeviceCode.java +++ b/src/main/java/com/microsoft/aad/msal4j/DeviceCode.java @@ -55,13 +55,13 @@ public final class DeviceCode { @Getter(AccessLevel.PROTECTED) @Setter(AccessLevel.PROTECTED) - private transient String correlationId = null; + private transient String correlationId = null; @Getter(AccessLevel.PROTECTED) @Setter(AccessLevel.PROTECTED) - private transient String clientId = null; + private transient String clientId = null; @Getter(AccessLevel.PROTECTED) @Setter(AccessLevel.PROTECTED) - private transient String scopes = null; + private transient String scopes = null; } diff --git a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeAuthorizationGrant.java b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeAuthorizationGrant.java index 7894e2de..545e3472 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeAuthorizationGrant.java +++ b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeAuthorizationGrant.java @@ -19,9 +19,9 @@ class DeviceCodeAuthorizationGrant extends AbstractMsalAuthorizationGrant { private String correlationId; /** - * Create a new device code grant object from a device code and a resource. + * Create a new device code grant object from a device code and a resource. * - * @param scopes The resource for which the device code was acquired. + * @param scopes The resource for which the device code was acquired. */ DeviceCodeAuthorizationGrant(DeviceCode deviceCode, final String scopes, ClaimsRequest claims) { this.deviceCode = deviceCode; diff --git a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowParameters.java b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowParameters.java index 6dad9948..1cdd910d 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowParameters.java @@ -33,7 +33,7 @@ public class DeviceCodeFlowParameters implements IAcquireTokenParameters { * Receives the device code returned from the first step of Oauth2.0 device code flow. The * {@link DeviceCode#verificationUri} and the {@link DeviceCode#userCode} should be shown * to the end user. - * + *

* For more details, see https://aka.ms/msal4j-device-code */ @NonNull @@ -56,12 +56,13 @@ private static DeviceCodeFlowParametersBuilder builder() { /** * Builder for {@link DeviceCodeFlowParameters} - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param deviceCodeConsumer {@link Consumer} of {@link DeviceCode} * @return builder that can be used to construct DeviceCodeFlowParameters */ public static DeviceCodeFlowParametersBuilder builder - (Set scopes, Consumer deviceCodeConsumer) { + (Set scopes, Consumer deviceCodeConsumer) { validateNotEmpty("scopes", scopes); diff --git a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowRequest.java b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowRequest.java index 4d1bcd1c..10ad0cc6 100644 --- a/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/DeviceCodeFlowRequest.java @@ -51,7 +51,7 @@ DeviceCode acquireDeviceCode(String url, this.requestContext(), serviceBundle); - if(response.statusCode() != HttpHelper.HTTP_STATUS_200){ + if (response.statusCode() != HttpHelper.HTTP_STATUS_200) { throw MsalServiceExceptionFactory.fromHttpResponse(response); } @@ -90,7 +90,7 @@ private DeviceCode parseJsonToDeviceCodeAndSetParameters( result = JsonHelper.convertJsonToObject(json, DeviceCode.class); String correlationIdHeader = headers.get(HttpHeaders.CORRELATION_ID_HEADER_NAME); - if(correlationIdHeader != null){ + if (correlationIdHeader != null) { result.correlationId(correlationIdHeader); } diff --git a/src/main/java/com/microsoft/aad/msal4j/Event.java b/src/main/java/com/microsoft/aad/msal4j/Event.java index 6861073b..9648ed28 100644 --- a/src/main/java/com/microsoft/aad/msal4j/Event.java +++ b/src/main/java/com/microsoft/aad/msal4j/Event.java @@ -12,7 +12,7 @@ import java.util.HashMap; import java.util.Map; -abstract class Event extends HashMap{ +abstract class Event extends HashMap { final static String EVENT_NAME_KEY = "event_name"; final static String START_TIME_KEY = "start_time"; @@ -22,11 +22,11 @@ abstract class Event extends HashMap{ private long startTimeStamp; - Event(String eventName){ + Event(String eventName) { this(eventName, new HashMap<>()); } - Event(String eventName, Map predefined){ + Event(String eventName, Map predefined) { super(predefined); this.put(EVENT_NAME_KEY, eventName); @@ -35,28 +35,28 @@ abstract class Event extends HashMap{ this.put(ELAPSED_TIME_KEY, "-1"); } - void stop(){ - long duration = Instant.now().toEpochMilli() - startTimeStamp; + void stop() { + long duration = Instant.now().toEpochMilli() - startTimeStamp; this.put(ELAPSED_TIME_KEY, Long.toString(duration)); } - static String scrubTenant(URI uri){ - if(!uri.isAbsolute()){ + static String scrubTenant(URI uri) { + if (!uri.isAbsolute()) { throw new IllegalArgumentException("Requires an absolute URI"); } - if(!AadInstanceDiscoveryProvider.TRUSTED_HOSTS_SET.contains(uri.getHost())){ + if (!AadInstanceDiscoveryProvider.TRUSTED_HOSTS_SET.contains(uri.getHost())) { return null; } String[] segment = uri.getPath().split("/"); - if(segment.length >= 2){ - if(segment[1].equals("tfp") && segment.length >= 3){ + if (segment.length >= 2) { + if (segment[1].equals("tfp") && segment.length >= 3) { segment[2] = TENANT_PLACEHOLDER; } else { segment[1] = TENANT_PLACEHOLDER; } - if(segment.length >= 4 && segment[2].equals("userrealm")){ + if (segment.length >= 4 && segment[2].equals("userrealm")) { segment[3] = USERNAME_PLACEHOLDER; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/EventKey.java b/src/main/java/com/microsoft/aad/msal4j/EventKey.java index 5b50374a..106a36ff 100644 --- a/src/main/java/com/microsoft/aad/msal4j/EventKey.java +++ b/src/main/java/com/microsoft/aad/msal4j/EventKey.java @@ -9,7 +9,7 @@ class EventKey { private String requestId; private String eventName; - EventKey(String requestId, Event event){ + EventKey(String requestId, Event event) { this.requestId = requestId; this.eventName = event.get(Event.EVENT_NAME_KEY); } @@ -24,9 +24,9 @@ public String getEventName() { @Override public boolean equals(Object obj) { - if(obj == null) return false; - if(!(obj instanceof EventKey)) return false; - if(obj == this) return true; + if (obj == null) return false; + if (!(obj instanceof EventKey)) return false; + if (obj == this) return true; EventKey eventKey = (EventKey) obj; return Objects.equals(requestId, eventKey.getRequestId()) && @@ -34,8 +34,7 @@ public boolean equals(Object obj) { } @Override - public int hashCode() - { + public int hashCode() { return Objects.hash(requestId, eventName); } diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpEvent.java b/src/main/java/com/microsoft/aad/msal4j/HttpEvent.java index ba4b7b79..f7547472 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpEvent.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpEvent.java @@ -9,7 +9,7 @@ import static com.microsoft.aad.msal4j.TelemetryConstants.EVENT_NAME_PREFIX; -class HttpEvent extends Event{ +class HttpEvent extends Event { private final static String HTTP_PATH_KEY = EVENT_NAME_PREFIX + "http_path"; private final static String USER_AGENT_KEY = EVENT_NAME_PREFIX + "user_agent"; private final static String QUERY_PARAMETERS_KEY = EVENT_NAME_PREFIX + "query_parameters"; @@ -20,76 +20,76 @@ class HttpEvent extends Event{ private final static String REQUEST_ID_HEADER_KEY = EVENT_NAME_PREFIX + "request_id_header"; private final static String TOKEN_AGEN_KEY = EVENT_NAME_PREFIX + "token_age"; private final static String SPE_INFO_KEY = EVENT_NAME_PREFIX + "spe_info"; - private final static String SERVER_ERROR_CODE_KEY = EVENT_NAME_PREFIX + "server_error_code"; + private final static String SERVER_ERROR_CODE_KEY = EVENT_NAME_PREFIX + "server_error_code"; private final static String SERVER_SUB_ERROR_CODE_KEY = EVENT_NAME_PREFIX + "server_sub_error_code"; - HttpEvent(){ + HttpEvent() { super(TelemetryConstants.HTTP_EVENT_NAME_KEY); } - void setHttpPath(URI httpPath){ + void setHttpPath(URI httpPath) { this.put(HTTP_PATH_KEY, scrubTenant(httpPath)); } - void setUserAgent(String userAgent){ + void setUserAgent(String userAgent) { this.put(USER_AGENT_KEY, userAgent.toLowerCase(Locale.ROOT)); } - void setQueryParameters(String queryParameters){ + void setQueryParameters(String queryParameters) { this.put(QUERY_PARAMETERS_KEY, String.join("&", parseQueryParametersAndReturnKeys(queryParameters))); } - void setApiVersion(String apiVersion){ + void setApiVersion(String apiVersion) { this.put(API_VERSION_KEY, apiVersion.toLowerCase()); } - void setHttpResponseStatus(Integer httpResponseStatus){ + void setHttpResponseStatus(Integer httpResponseStatus) { this.put(RESPONSE_CODE_KEY, httpResponseStatus.toString().toLowerCase()); } - void setHttpMethod(String httpMethod){ + void setHttpMethod(String httpMethod) { this.put(HTTP_METHOD_KEY, httpMethod); } - void setOauthErrorCode(String oauthErrorCode){ + void setOauthErrorCode(String oauthErrorCode) { this.put(OAUTH_ERROR_CODE_KEY, oauthErrorCode.toLowerCase()); } - void setRequestIdHeader(String requestIdHeader){ + void setRequestIdHeader(String requestIdHeader) { this.put(REQUEST_ID_HEADER_KEY, requestIdHeader.toLowerCase()); } - private void setTokenAge(String tokenAge){ + private void setTokenAge(String tokenAge) { this.put(TOKEN_AGEN_KEY, tokenAge.toLowerCase()); } - private void setSpeInfo(String speInfo){ + private void setSpeInfo(String speInfo) { this.put(SPE_INFO_KEY, speInfo.toLowerCase()); } - private void setServerErrorCode(String serverErrorCode){ + private void setServerErrorCode(String serverErrorCode) { this.put(SERVER_ERROR_CODE_KEY, serverErrorCode.toLowerCase()); } - private void setSubServerErrorCode(String subServerErrorCode){ + private void setSubServerErrorCode(String subServerErrorCode) { this.put(SERVER_SUB_ERROR_CODE_KEY, subServerErrorCode.toLowerCase()); } - void setXmsClientTelemetryInfo(XmsClientTelemetryInfo xmsClientTelemetryInfo){ + void setXmsClientTelemetryInfo(XmsClientTelemetryInfo xmsClientTelemetryInfo) { this.setTokenAge(xmsClientTelemetryInfo.getTokenAge()); this.setSpeInfo(xmsClientTelemetryInfo.getSpeInfo()); this.setServerErrorCode(xmsClientTelemetryInfo.getServerErrorCode()); this.setSubServerErrorCode(xmsClientTelemetryInfo.getServerSubErrorCode()); } - private ArrayList parseQueryParametersAndReturnKeys(String queryParams){ + private ArrayList parseQueryParametersAndReturnKeys(String queryParams) { ArrayList queryKeys = new ArrayList<>(); String[] queryStrings = queryParams.split("&"); - for(String queryString: queryStrings){ - String[] queryPairs = queryString.split("="); - if(queryPairs.length == 2 && + for (String queryString : queryStrings) { + String[] queryPairs = queryString.split("="); + if (queryPairs.length == 2 && !StringHelper.isBlank(queryPairs[0]) && - !StringHelper.isBlank(queryPairs[1])){ + !StringHelper.isBlank(queryPairs[1])) { queryKeys.add(queryPairs[0].toLowerCase(Locale.ROOT)); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpHelper.java b/src/main/java/com/microsoft/aad/msal4j/HttpHelper.java index 30d27735..2c088fd5 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpHelper.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpHelper.java @@ -25,7 +25,7 @@ class HttpHelper { public static final int HTTP_STATUS_429 = 429; public static final int HTTP_STATUS_500 = 500; - private HttpHelper(){ + private HttpHelper() { } static IHttpResponse executeHttpRequest(HttpRequest httpRequest, @@ -146,8 +146,7 @@ private static Integer getRetryAfterHeader(IHttpResponse httpResponse) { if (headerValue > 0 && headerValue <= ThrottlingCache.MAX_THROTTLING_TIME_SEC) { return headerValue; } - } - catch (NumberFormatException ex){ + } catch (NumberFormatException ex) { log.warn("Failed to parse value of Retry-After header - NumberFormatException"); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpListener.java b/src/main/java/com/microsoft/aad/msal4j/HttpListener.java index 7228c0c2..622e1db7 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpListener.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpListener.java @@ -30,14 +30,14 @@ void startListener(int port, HttpHandler httpHandler) { this.port = server.getAddress().getPort(); server.start(); LOG.debug("Http listener started. Listening on port: " + port); - } catch (Exception e){ + } catch (Exception e) { throw new MsalClientException(e.getMessage(), AuthenticationErrorCode.UNABLE_TO_START_HTTP_LISTENER); } } - void stopListener(){ - if(server != null){ + void stopListener() { + if (server != null) { server.stop(0); LOG.debug("Http listener stopped"); diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpRequest.java b/src/main/java/com/microsoft/aad/msal4j/HttpRequest.java index 7a5824ba..ff93e362 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpRequest.java @@ -38,26 +38,26 @@ public class HttpRequest { */ private String body; - HttpRequest(HttpMethod httpMethod, String url){ + HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; this.url = createUrlFromString(url); } - HttpRequest(HttpMethod httpMethod, String url, Map headers){ + HttpRequest(HttpMethod httpMethod, String url, Map headers) { this.httpMethod = httpMethod; this.url = createUrlFromString(url); this.headers = headers; } - HttpRequest(HttpMethod httpMethod, String url, String body){ + HttpRequest(HttpMethod httpMethod, String url, String body) { this.httpMethod = httpMethod; this.url = createUrlFromString(url); this.body = body; } HttpRequest(HttpMethod httpMethod, - String url, Map headers, - String body){ + String url, Map headers, + String body) { this.httpMethod = httpMethod; this.url = createUrlFromString(url); this.headers = headers; @@ -68,20 +68,20 @@ public class HttpRequest { * @param headerName Name of HTTP header name * @return Value of HTTP header */ - public String headerValue(String headerName){ + public String headerValue(String headerName) { - if(headerName == null || headers == null){ + if (headerName == null || headers == null) { return null; } return headers.get(headerName); } - private URL createUrlFromString(String stringUrl){ + private URL createUrlFromString(String stringUrl) { URL url; - try{ + try { url = new URL(stringUrl); - } catch(MalformedURLException e){ + } catch (MalformedURLException e) { throw new MsalClientException(e); } diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpResponse.java b/src/main/java/com/microsoft/aad/msal4j/HttpResponse.java index ef5a7d5e..1ad259de 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpResponse.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpResponse.java @@ -15,7 +15,7 @@ /** * HTTP response */ -@Accessors(fluent=true) +@Accessors(fluent = true) @Getter public class HttpResponse implements IHttpResponse { @@ -28,7 +28,7 @@ public class HttpResponse implements IHttpResponse { /** * HTTP response headers */ - private Map> headers = new HashMap<>(); + private Map> headers = new HashMap<>(); /** * HTTP response body @@ -40,8 +40,8 @@ public class HttpResponse implements IHttpResponse { * @param responseHeaders Map of HTTP headers returned from HTTP client */ public void addHeaders(Map> responseHeaders) { - for(Map.Entry> entry: responseHeaders.entrySet()){ - if(entry.getKey() == null){ + for (Map.Entry> entry : responseHeaders.entrySet()) { + if (entry.getKey() == null) { continue; } @@ -54,7 +54,7 @@ public void addHeaders(Map> responseHeaders) { } } - private void addHeader(final String name, final String ... values){ + private void addHeader(final String name, final String... values) { if (values != null && values.length > 0) { headers.put(name, Arrays.asList(values)); } else { diff --git a/src/main/java/com/microsoft/aad/msal4j/HttpUtils.java b/src/main/java/com/microsoft/aad/msal4j/HttpUtils.java index 58831072..d1373b67 100644 --- a/src/main/java/com/microsoft/aad/msal4j/HttpUtils.java +++ b/src/main/java/com/microsoft/aad/msal4j/HttpUtils.java @@ -8,15 +8,15 @@ class HttpUtils { - static String headerValue(Map> headers, String headerName){ + static String headerValue(Map> headers, String headerName) { - if(headerName == null || headers == null){ + if (headerName == null || headers == null) { return null; } List headerValue = headers.get(headerName); - if(headerValue == null || headerValue.isEmpty()){ + if (headerValue == null || headerValue.isEmpty()) { return null; } diff --git a/src/main/java/com/microsoft/aad/msal4j/IAccount.java b/src/main/java/com/microsoft/aad/msal4j/IAccount.java index 749d2cde..7bb71500 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IAccount.java +++ b/src/main/java/com/microsoft/aad/msal4j/IAccount.java @@ -9,7 +9,6 @@ /** * Interface representing a single user account. An IAccount is returned in the {@link IAuthenticationResult} * property, and is used as parameter in {@link SilentParameters#builder(Set, IAccount)} )} - * */ public interface IAccount extends Serializable { diff --git a/src/main/java/com/microsoft/aad/msal4j/IAcquireTokenParameters.java b/src/main/java/com/microsoft/aad/msal4j/IAcquireTokenParameters.java index c0fab78e..410c0f83 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IAcquireTokenParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/IAcquireTokenParameters.java @@ -11,6 +11,8 @@ */ interface IAcquireTokenParameters { Set scopes(); + ClaimsRequest claims(); + Map extraHttpHeaders(); } diff --git a/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java b/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java index 922c71f0..65412b39 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java +++ b/src/main/java/com/microsoft/aad/msal4j/IClientApplicationBase.java @@ -70,10 +70,11 @@ interface IClientApplicationBase { * Computes the URL of the authorization request letting the user sign-in and consent to the * application. The URL target the /authorize endpoint of the authority configured in the * application object. - * + *

* Once the user successfully authenticates, the response should contain an authorization code, * which can then be passed in to{@link AbstractClientApplicationBase#acquireToken(AuthorizationCodeParameters)} * to be exchanged for a token + * * @param parameters {@link AuthorizationRequestUrlParameters} * @return url of the authorization endpoint where the user can sign-in and consent to the application. */ @@ -119,7 +120,6 @@ CompletableFuture acquireTokenSilently(SilentParameters p * Removes IAccount from the cache * * @param account instance of Account to be removed from cache - * * @return {@link CompletableFuture} object representing account removal task. */ CompletableFuture removeAccount(IAccount account); diff --git a/src/main/java/com/microsoft/aad/msal4j/IClientAssertion.java b/src/main/java/com/microsoft/aad/msal4j/IClientAssertion.java index e82de558..0426315a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IClientAssertion.java +++ b/src/main/java/com/microsoft/aad/msal4j/IClientAssertion.java @@ -6,10 +6,10 @@ /** * Credential type containing an assertion of type * "urn:ietf:params:oauth:token-type:jwt". - * + *

* For more details, see https://aka.ms/msal4j-client-credentials */ -public interface IClientAssertion extends IClientCredential{ +public interface IClientAssertion extends IClientCredential { /** * @return Jwt token encoded as a base64 URL encoded string diff --git a/src/main/java/com/microsoft/aad/msal4j/IClientCertificate.java b/src/main/java/com/microsoft/aad/msal4j/IClientCertificate.java index 2a681539..e9281f91 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IClientCertificate.java +++ b/src/main/java/com/microsoft/aad/msal4j/IClientCertificate.java @@ -10,10 +10,10 @@ /** * Credential type containing X509 public certificate and RSA private key. - * - * For more details, see https://aka.ms/msal4j-client-credentials + *

+ * For more details, see https://aka.ms/msal4j-client-credentials */ -public interface IClientCertificate extends IClientCredential{ +public interface IClientCertificate extends IClientCredential { /** * Returns private key of the credential. @@ -27,7 +27,7 @@ public interface IClientCertificate extends IClientCredential{ * * @return base64 encoded string * @throws CertificateEncodingException if an encoding error occurs - * @throws NoSuchAlgorithmException if requested algorithm is not available in the environment + * @throws NoSuchAlgorithmException if requested algorithm is not available in the environment */ String publicCertificateHash() throws CertificateEncodingException, NoSuchAlgorithmException; diff --git a/src/main/java/com/microsoft/aad/msal4j/IClientCredential.java b/src/main/java/com/microsoft/aad/msal4j/IClientCredential.java index e1b6d959..a62bba2f 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IClientCredential.java +++ b/src/main/java/com/microsoft/aad/msal4j/IClientCredential.java @@ -5,7 +5,7 @@ /** * Interface representing an application credential - * + *

* For more details, see https://aka.ms/msal4j-client-credentials */ public interface IClientCredential { diff --git a/src/main/java/com/microsoft/aad/msal4j/IClientSecret.java b/src/main/java/com/microsoft/aad/msal4j/IClientSecret.java index 568a8786..0dbbabca 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IClientSecret.java +++ b/src/main/java/com/microsoft/aad/msal4j/IClientSecret.java @@ -5,10 +5,10 @@ /** * Representation of client credential containing a secret in string format - * + *

* For more details, see https://aka.ms/msal4j-client-credentials */ -public interface IClientSecret extends IClientCredential{ +public interface IClientSecret extends IClientCredential { /** * @return secret secret of application requesting a token diff --git a/src/main/java/com/microsoft/aad/msal4j/IConfidentialClientApplication.java b/src/main/java/com/microsoft/aad/msal4j/IConfidentialClientApplication.java index 5381a704..f3bb8414 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IConfidentialClientApplication.java +++ b/src/main/java/com/microsoft/aad/msal4j/IConfidentialClientApplication.java @@ -23,6 +23,7 @@ public interface IConfidentialClientApplication extends IClientApplicationBase { * Acquires tokens from the authority configured in the application, for the confidential client * itself. It will by default attempt to get tokens from the token cache. If no tokens are found, * it falls back to acquiring them via client credentials from the STS + * * @param parameters instance of {@link ClientCredentialParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} */ @@ -34,7 +35,7 @@ public interface IConfidentialClientApplication extends IClientApplicationBase { * using the On-Behalf-Of flow. It will by default attempt to get tokens from the token cache. * This confidential client application was itself called with an acces token which is provided in * the {@link UserAssertion} field of {@link OnBehalfOfParameters}. - * + *

* When serializing/deserializing the in-memory token cache to permanent storage, there should be * a token cache per incoming access token, where the hash of the incoming access token can be used * as the token cache key. Access tokens are usually only valid for a 1 hour period of time, @@ -43,6 +44,7 @@ public interface IConfidentialClientApplication extends IClientApplicationBase { * token caches, an eviction policy should be set. For example, a token cache that * is more than a couple of hours old can be deemed expired and therefore evicted from the * serialized token cache. + * * @param parameters instance of {@link OnBehalfOfParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} */ diff --git a/src/main/java/com/microsoft/aad/msal4j/IHttpClient.java b/src/main/java/com/microsoft/aad/msal4j/IHttpClient.java index b14001d4..c31c141c 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IHttpClient.java +++ b/src/main/java/com/microsoft/aad/msal4j/IHttpClient.java @@ -6,18 +6,19 @@ /** * Interface to be implemented when configuring http client for {@link IPublicClientApplication} or * {@link IConfidentialClientApplication}. - * + *

* For more details, see https://aka.ms/msal4j-http-client */ public interface IHttpClient { /** - * Should implement execution of outgoing HTTP request with HTTP client of choice. Adapts - * response returned from HTTP client to {@link IHttpResponse} + * Should implement execution of outgoing HTTP request with HTTP client of choice. Adapts + * response returned from HTTP client to {@link IHttpResponse} + * * @param httpRequest {@link HttpRequest} * @return {@link IHttpResponse}. * @throws Exception Non-recoverable exception. Recoverable exceptions should be handled by the - * IHttpClient implementation + * IHttpClient implementation */ IHttpResponse send(HttpRequest httpRequest) throws Exception; } diff --git a/src/main/java/com/microsoft/aad/msal4j/IHttpResponse.java b/src/main/java/com/microsoft/aad/msal4j/IHttpResponse.java index 9757b64e..f1fc5430 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IHttpResponse.java +++ b/src/main/java/com/microsoft/aad/msal4j/IHttpResponse.java @@ -17,7 +17,6 @@ public interface IHttpResponse { int statusCode(); /** - * * @return HTTP response headers */ Map> headers(); diff --git a/src/main/java/com/microsoft/aad/msal4j/IPublicClientApplication.java b/src/main/java/com/microsoft/aad/msal4j/IPublicClientApplication.java index aed245bf..b6a15173 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IPublicClientApplication.java +++ b/src/main/java/com/microsoft/aad/msal4j/IPublicClientApplication.java @@ -15,6 +15,7 @@ public interface IPublicClientApplication extends IClientApplicationBase { /** * Acquires tokens from the authority configured in the application via Username/Password authentication. + * * @param parameters instance of {@link UserNamePasswordParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} */ @@ -22,6 +23,7 @@ public interface IPublicClientApplication extends IClientApplicationBase { /** * Acquires tokens from the authority configured in the application via Integrated Windows Authentication. + * * @param parameters instance of {@link IntegratedWindowsAuthenticationParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} */ @@ -35,13 +37,14 @@ public interface IPublicClientApplication extends IClientApplicationBase { * End-user should be instructed to use another device to connect to the authorization server to approve the access request. * Since the client cannot receive incoming requests, it polls the authorization server repeatedly * until the end-user completes the approval process. + * * @param parameters instance of {@link DeviceCodeFlowParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} * @throws MsalException thrown if authorization is pending or another error occurred. - * If the errorCode of the exception is AuthenticationErrorCode.AUTHORIZATION_PENDING, - * the call needs to be retried until the AccessToken is returned. - * DeviceCode.interval - The minimum amount of time in seconds that the client - * SHOULD wait between polling requests to the token endpoint + * If the errorCode of the exception is AuthenticationErrorCode.AUTHORIZATION_PENDING, + * the call needs to be retried until the AccessToken is returned. + * DeviceCode.interval - The minimum amount of time in seconds that the client + * SHOULD wait between polling requests to the token endpoint */ CompletableFuture acquireToken(DeviceCodeFlowParameters parameters); @@ -51,6 +54,7 @@ public interface IPublicClientApplication extends IClientApplicationBase { * and do multi-factor authentication if such a policy is enabled on the Azure AD tenant. * System browser can behavior can be customized via {@link InteractiveRequestParameters#systemBrowserOptions}. * For more information, see https://aka.ms/msal4j-interactive-request + * * @param parameters instance of {@link InteractiveRequestParameters} * @return {@link CompletableFuture} containing an {@link IAuthenticationResult} */ diff --git a/src/main/java/com/microsoft/aad/msal4j/ITelemetry.java b/src/main/java/com/microsoft/aad/msal4j/ITelemetry.java index 1109a99c..0194412a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ITelemetry.java +++ b/src/main/java/com/microsoft/aad/msal4j/ITelemetry.java @@ -5,6 +5,8 @@ interface ITelemetry { void startEvent(String requestId, Event eventToStart); + void stopEvent(String requestId, Event eventToEnd); + void flush(String requestId, String clientId); } diff --git a/src/main/java/com/microsoft/aad/msal4j/ITenantProfile.java b/src/main/java/com/microsoft/aad/msal4j/ITenantProfile.java index 30a77c8d..32f7444a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ITenantProfile.java +++ b/src/main/java/com/microsoft/aad/msal4j/ITenantProfile.java @@ -9,7 +9,6 @@ /** * Interface representing a single tenant profile. ITenantProfiles are made available through the * {@link IAccount#getTenantProfiles()} method of an Account - * */ public interface ITenantProfile extends Serializable { diff --git a/src/main/java/com/microsoft/aad/msal4j/ITokenCache.java b/src/main/java/com/microsoft/aad/msal4j/ITokenCache.java index 52abbf1c..7e9d8532 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ITokenCache.java +++ b/src/main/java/com/microsoft/aad/msal4j/ITokenCache.java @@ -5,7 +5,7 @@ /** * Interface representing security token cache persistence - * + *

* For more details, see https://aka.ms/msal4j-token-cache */ public interface ITokenCache { diff --git a/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessAspect.java b/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessAspect.java index 3181a929..32ee4a88 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessAspect.java +++ b/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessAspect.java @@ -5,7 +5,7 @@ /** * Interface representing operation of executing code before and after cache access. - * + *

* For more details, see https://aka.ms/msal4j-token-cache */ public interface ITokenCacheAccessAspect { diff --git a/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessContext.java b/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessContext.java index 71ccee89..9fbd761c 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessContext.java +++ b/src/main/java/com/microsoft/aad/msal4j/ITokenCacheAccessContext.java @@ -5,7 +5,7 @@ /** * Interface representing context in which the token cache is accessed - * + *

* For more details, see https://aka.ms/msal4j-token-cache */ public interface ITokenCacheAccessContext { diff --git a/src/main/java/com/microsoft/aad/msal4j/IdToken.java b/src/main/java/com/microsoft/aad/msal4j/IdToken.java index c0930530..dbdcbce6 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IdToken.java +++ b/src/main/java/com/microsoft/aad/msal4j/IdToken.java @@ -32,7 +32,7 @@ class IdToken { protected String subject; @JsonProperty("aud") - protected String audience ; + protected String audience; @JsonProperty("exp") protected Long expirationTime; diff --git a/src/main/java/com/microsoft/aad/msal4j/IdTokenCacheEntity.java b/src/main/java/com/microsoft/aad/msal4j/IdTokenCacheEntity.java index 21052f8a..84c75e71 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IdTokenCacheEntity.java +++ b/src/main/java/com/microsoft/aad/msal4j/IdTokenCacheEntity.java @@ -22,7 +22,7 @@ class IdTokenCacheEntity extends Credential { @JsonProperty("realm") protected String realm; - String getKey(){ + String getKey() { List keyParts = new ArrayList<>(); keyParts.add(homeAccountId); diff --git a/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationParameters.java b/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationParameters.java index ba9508e1..853d871a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationParameters.java @@ -14,9 +14,9 @@ /** * Object containing parameters for Integrated Windows Authentication. Can be used as parameter to - * {@link PublicClientApplication#acquireToken(IntegratedWindowsAuthenticationParameters)}` - * - * For more details, see https://aka.ms/msal4j-iwa + * {@link PublicClientApplication#acquireToken(IntegratedWindowsAuthenticationParameters)}` + *

+ * For more details, see https://aka.ms/msal4j-iwa */ @Builder @Accessors(fluent = true) @@ -54,7 +54,8 @@ private static IntegratedWindowsAuthenticationParametersBuilder builder() { /** * Builder for {@link IntegratedWindowsAuthenticationParameters} - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param username identifier of user account for which to acquire token for. Usually in UPN format, * e.g. john.doe@contoso.com. * @return builder that can be used to construct IntegratedWindowsAuthenticationParameters diff --git a/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationRequest.java b/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationRequest.java index 797662cd..ca20a455 100644 --- a/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/IntegratedWindowsAuthenticationRequest.java @@ -3,16 +3,16 @@ package com.microsoft.aad.msal4j; -class IntegratedWindowsAuthenticationRequest extends MsalRequest{ +class IntegratedWindowsAuthenticationRequest extends MsalRequest { IntegratedWindowsAuthenticationRequest(IntegratedWindowsAuthenticationParameters parameters, PublicClientApplication application, - RequestContext requestContext){ - super(application, createAuthenticationGrant(parameters), requestContext); + RequestContext requestContext) { + super(application, createAuthenticationGrant(parameters), requestContext); } private static AbstractMsalAuthorizationGrant createAuthenticationGrant - (IntegratedWindowsAuthenticationParameters parameters){ + (IntegratedWindowsAuthenticationParameters parameters) { return new IntegratedWindowsAuthorizationGrant(parameters.scopes(), parameters.username(), parameters.claims()); } diff --git a/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredCache.java b/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredCache.java index 618f4071..bb8982ff 100644 --- a/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredCache.java +++ b/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredCache.java @@ -45,11 +45,8 @@ private static boolean isCacheEntityValid(CachedEntity cachedEntity) { long expirationTimestamp = cachedEntity.expirationTimestamp; long currentTimestamp = System.currentTimeMillis(); - if (currentTimestamp < expirationTimestamp && - currentTimestamp >= expirationTimestamp - DEFAULT_CACHING_TIME_SEC * 1000) { - return true; - } - return false; + return currentTimestamp < expirationTimestamp && + currentTimestamp >= expirationTimestamp - DEFAULT_CACHING_TIME_SEC * 1000; } private static class CachedEntity { @@ -63,13 +60,13 @@ public CachedEntity(MsalInteractionRequiredException exception, long expirationT } } - private static void removeInvalidCacheEntities(){ - if(requestsToCache.size() > CACHE_SIZE_LIMIT_TO_TRIGGER_EXPIRED_ENTITIES_REMOVAL){ + private static void removeInvalidCacheEntities() { + if (requestsToCache.size() > CACHE_SIZE_LIMIT_TO_TRIGGER_EXPIRED_ENTITIES_REMOVAL) { requestsToCache.values().removeIf(value -> !isCacheEntityValid(value)); } } - static void clear(){ + static void clear() { requestsToCache.clear(); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredExceptionReason.java b/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredExceptionReason.java index 9ad18790..e698eace 100644 --- a/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredExceptionReason.java +++ b/src/main/java/com/microsoft/aad/msal4j/InteractionRequiredExceptionReason.java @@ -47,18 +47,18 @@ public enum InteractionRequiredExceptionReason { private String error; - InteractionRequiredExceptionReason(String error){ + InteractionRequiredExceptionReason(String error) { this.error = error; } - static InteractionRequiredExceptionReason fromSubErrorString(String subError){ - if(StringHelper.isBlank(subError)){ + static InteractionRequiredExceptionReason fromSubErrorString(String subError) { + if (StringHelper.isBlank(subError)) { return NONE; } - for(InteractionRequiredExceptionReason reason: - InteractionRequiredExceptionReason.values()){ - if(reason.error.equalsIgnoreCase(subError)){ + for (InteractionRequiredExceptionReason reason : + InteractionRequiredExceptionReason.values()) { + if (reason.error.equalsIgnoreCase(subError)) { return reason; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/InteractiveRequest.java b/src/main/java/com/microsoft/aad/msal4j/InteractiveRequest.java index cd7685c6..2c024bb9 100644 --- a/src/main/java/com/microsoft/aad/msal4j/InteractiveRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/InteractiveRequest.java @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicReference; @Accessors(fluent = true) -class InteractiveRequest extends MsalRequest{ +class InteractiveRequest extends MsalRequest { @Getter(AccessLevel.PACKAGE) private AtomicReference> futureReference; @@ -37,7 +37,7 @@ class InteractiveRequest extends MsalRequest{ InteractiveRequest(InteractiveRequestParameters parameters, AtomicReference> futureReference, PublicClientApplication publicClientApplication, - RequestContext requestContext){ + RequestContext requestContext) { super(publicClientApplication, null, requestContext); @@ -47,8 +47,8 @@ class InteractiveRequest extends MsalRequest{ validateRedirectUrl(parameters.redirectUri()); } - URL authorizationUrl(){ - if(this.authorizationUrl == null) { + URL authorizationUrl() { + if (this.authorizationUrl == null) { authorizationUrl = createAuthorizationUrl(); } return authorizationUrl; @@ -71,12 +71,12 @@ private void validateRedirectUrl(URI redirectUri) { " the create the InteractiveRequestParameters object", redirectUri.toString()), AuthenticationErrorCode.LOOPBACK_REDIRECT_URI); } - } catch (Exception exception){ + } catch (Exception exception) { throw new MsalClientException(exception); } } - private URL createAuthorizationUrl(){ + private URL createAuthorizationUrl() { AuthorizationRequestUrlParameters.Builder authorizationRequestUrlBuilder = AuthorizationRequestUrlParameters diff --git a/src/main/java/com/microsoft/aad/msal4j/InteractiveRequestParameters.java b/src/main/java/com/microsoft/aad/msal4j/InteractiveRequestParameters.java index 37726dd2..4c903692 100644 --- a/src/main/java/com/microsoft/aad/msal4j/InteractiveRequestParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/InteractiveRequestParameters.java @@ -20,7 +20,7 @@ /** * Object containing parameters for interactive requests. Can be used as parameter to * {@link PublicClientApplication#acquireToken(InteractiveRequestParameters)}. - * + *

* For more details, see https://aka.ms/msal4j-interactive-request. */ @Builder diff --git a/src/main/java/com/microsoft/aad/msal4j/JsonHelper.java b/src/main/java/com/microsoft/aad/msal4j/JsonHelper.java index dbbad057..f0dea645 100644 --- a/src/main/java/com/microsoft/aad/msal4j/JsonHelper.java +++ b/src/main/java/com/microsoft/aad/msal4j/JsonHelper.java @@ -25,7 +25,7 @@ class JsonHelper { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } - private JsonHelper(){ + private JsonHelper() { } static T convertJsonToObject(final String json, final Class tClass) { @@ -64,8 +64,7 @@ public static String formCapabilitiesJson(Set clientCapabilities) { cr.requestClaimInAccessToken("xms_cc", capabilitiesValues); return cr.formatAsJSONString(); - } - else { + } else { return null; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/JwtHelper.java b/src/main/java/com/microsoft/aad/msal4j/JwtHelper.java index 7d2f2abb..e6b5171e 100644 --- a/src/main/java/com/microsoft/aad/msal4j/JwtHelper.java +++ b/src/main/java/com/microsoft/aad/msal4j/JwtHelper.java @@ -21,7 +21,7 @@ final class JwtHelper { static ClientAssertion buildJwt(String clientId, final ClientCertificate credential, - final String jwtAudience, boolean sendX5c) throws MsalClientException { + final String jwtAudience, boolean sendX5c) throws MsalClientException { if (StringHelper.isBlank(clientId)) { throw new IllegalArgumentException("clientId is null or empty"); } @@ -38,8 +38,8 @@ static ClientAssertion buildJwt(String clientId, final ClientCertificate credent .jwtID(UUID.randomUUID().toString()) .notBeforeTime(new Date(time)) .expirationTime(new Date(time - + Constants.AAD_JWT_TOKEN_LIFETIME_SECONDS - * 1000)) + + Constants.AAD_JWT_TOKEN_LIFETIME_SECONDS + * 1000)) .subject(clientId) .build(); @@ -47,9 +47,9 @@ static ClientAssertion buildJwt(String clientId, final ClientCertificate credent try { JWSHeader.Builder builder = new Builder(JWSAlgorithm.RS256); - if(sendX5c){ + if (sendX5c) { List certs = new ArrayList<>(); - for (String cert: credential.getEncodedPublicKeyCertificateChain()) { + for (String cert : credential.getEncodedPublicKeyCertificateChain()) { certs.add(new Base64(cert)); } builder.x509CertChain(certs); @@ -61,8 +61,7 @@ static ClientAssertion buildJwt(String clientId, final ClientCertificate credent final RSASSASigner signer = new RSASSASigner(credential.privateKey()); jwt.sign(signer); - } - catch (final Exception e) { + } catch (final Exception e) { throw new MsalClientException(e); } diff --git a/src/main/java/com/microsoft/aad/msal4j/MexParser.java b/src/main/java/com/microsoft/aad/msal4j/MexParser.java index cbb61d9c..8c5b2390 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MexParser.java +++ b/src/main/java/com/microsoft/aad/msal4j/MexParser.java @@ -11,6 +11,7 @@ import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.*; import java.util.Map.Entry; @@ -74,7 +75,7 @@ static BindingPolicy getPolicy(String mexResponse, PolicySelector policySelector builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(new ByteArrayInputStream( - mexResponse.getBytes(Charset.forName("UTF-8")))); + mexResponse.getBytes(StandardCharsets.UTF_8))); XPath xPath = XPathFactory.newInstance().newXPath(); NamespaceContextImpl nameSpace = new NamespaceContextImpl(); @@ -86,8 +87,7 @@ static BindingPolicy getPolicy(String mexResponse, PolicySelector policySelector log.debug("No matching policies"); return null; - } - else { + } else { Map bindings = getMatchingBindings( xmlDocument, xPath, policies, logPii); @@ -95,8 +95,7 @@ static BindingPolicy getPolicy(String mexResponse, PolicySelector policySelector log.debug("No matching bindings"); return null; - } - else { + } else { getPortsForPolicyBindings(xmlDocument, xPath, bindings, policies, logPii); return selectSingleMatchingPolicy(policies); } @@ -125,8 +124,7 @@ private static BindingPolicy selectSingleMatchingPolicy( if (pair.getValue().getUrl() != null) { if (pair.getValue().getVersion() == WSTrustVersion.WSTRUST13) { wstrust13 = pair.getValue(); - } - else if (pair.getValue().getVersion() == WSTrustVersion.WSTRUST2005) { + } else if (pair.getValue().getVersion() == WSTrustVersion.WSTRUST2005) { wstrust2005 = pair.getValue(); } } @@ -142,16 +140,15 @@ else if (pair.getValue().getVersion() == WSTrustVersion.WSTRUST2005) { } private static void getPortsForPolicyBindings(Document xmlDocument, - XPath xPath, Map bindings, - Map policies, boolean logPii) throws Exception { + XPath xPath, Map bindings, + Map policies, boolean logPii) throws Exception { NodeList portNodes = (NodeList) xPath.compile(PORT_XPATH).evaluate( xmlDocument, XPathConstants.NODESET); if (portNodes.getLength() == 0) { log.warn("No ports found"); - } - else { + } else { for (int i = 0; i < portNodes.getLength(); i++) { Node portNode = portNodes.item(i); String bindingId = portNode.getAttributes() @@ -173,19 +170,16 @@ private static void getPortsForPolicyBindings(Document xmlDocument, .getTextContent(); if (address != null && address.toLowerCase().startsWith( - "https://")) { + "https://")) { bindingPolicy.setUrl(address.trim()); - } - else { - if(logPii){ + } else { + if (logPii) { log.warn("Skipping insecure endpoint" + ": " + address); - } - else{ + } else { log.warn("Skipping insecure endpoint"); } } - } - else { + } else { throw new MsalClientException( "Error parsing WSTrustResponse: No address nodes on port", AuthenticationErrorCode.WSTRUST_INVALID_RESPONSE); @@ -227,7 +221,7 @@ private static Map getMatchingBindings( } private static WSTrustVersion checkSoapActionAndTransport(XPath xPath, - Node bindingNode, boolean logPii) throws XPathExpressionException { + Node bindingNode, boolean logPii) throws XPathExpressionException { NodeList soapTransportAttributes = null; String soapAction = null; String bindingName = bindingNode.getAttributes().getNamedItem("name") @@ -243,23 +237,20 @@ private static WSTrustVersion checkSoapActionAndTransport(XPath xPath, if (soapTransportAttributes != null && soapTransportAttributes.getLength() > 0 && soapTransportAttributes.item(0).getNodeValue() - .equalsIgnoreCase(SOAP_HTTP_TRANSPORT_VALUE)) { + .equalsIgnoreCase(SOAP_HTTP_TRANSPORT_VALUE)) { if (soapAction.equalsIgnoreCase(RST_SOAP_ACTION)) { - if(logPii){ + if (logPii) { log.debug("Found binding matching Action and Transport: " + bindingName); - } - else{ + } else { log.debug("Found binding matching Action and Transport"); } return WSTrustVersion.WSTRUST13; - } - else if (soapAction.equalsIgnoreCase(RST_SOAP_ACTION_2005)) { - if(logPii){ + } else if (soapAction.equalsIgnoreCase(RST_SOAP_ACTION_2005)) { + if (logPii) { log.debug("Binding node did not match soap Action or Transport: " + bindingName); - } - else{ + } else { log.debug("Binding node did not match soap Action or Transport"); } @@ -299,8 +290,8 @@ private static Map selectUsernamePasswordPoliciesWithExpr } private static Map selectIntegratedPoliciesWithExpression(Document xmlDocument, - XPath xPath, - String xpathExpression) throws XPathExpressionException { + XPath xPath, + String xpathExpression) throws XPathExpressionException { Map policies = new HashMap(); @@ -329,23 +320,20 @@ private static String checkPolicy(XPath xPath, Node node, boolean logPii) if (transportBindingNodes.getLength() > 0 && id != null) { policyId = id.getNodeValue(); - if(logPii){ + if (logPii) { log.debug("found matching policy id: " + policyId); - } - else{ + } else { log.debug("found matching policy"); } - } - else { + } else { String nodeValue = "none"; if (id != null) { nodeValue = id.getNodeValue(); } - if(logPii){ + if (logPii) { log.debug("potential policy did not match required transport binding: " + nodeValue); - } - else{ + } else { log.debug("potential policy did not match required transport binding"); } } @@ -353,7 +341,7 @@ private static String checkPolicy(XPath xPath, Node node, boolean logPii) } private static String checkPolicyIntegrated(XPath xPath, - Node node) throws XPathExpressionException { + Node node) throws XPathExpressionException { Node id = node.getAttributes().getNamedItem("wsu:Id"); String policyId = id.getNodeValue(); return policyId; diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalClientException.java b/src/main/java/com/microsoft/aad/msal4j/MsalClientException.java index ce0e4bc5..f30b9178 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalClientException.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalClientException.java @@ -4,23 +4,25 @@ package com.microsoft.aad.msal4j; /** - * Exception type thrown when and error occurs that is local to the library or the device. + * Exception type thrown when and error occurs that is local to the library or the device. */ public class MsalClientException extends MsalException { /** * Initializes a new instance of the exception class with a instance of Throwable + * * @param throwable the inner exception that is the cause of the current exception */ - public MsalClientException(final Throwable throwable){ + public MsalClientException(final Throwable throwable) { super(throwable); } /** * Initializes a new instance of the exception class with a specified error message + * * @param message the error message that explains the reason for the exception */ - public MsalClientException(final String message, final String errorCode){ + public MsalClientException(final String message, final String errorCode) { super(message, errorCode); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalException.java b/src/main/java/com/microsoft/aad/msal4j/MsalException.java index da03883b..a3944746 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalException.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalException.java @@ -22,6 +22,7 @@ public class MsalException extends RuntimeException { /** * Initializes a new instance of the exception class + * * @param throwable the inner exception that is the cause of the current exception */ public MsalException(final Throwable throwable) { @@ -30,6 +31,7 @@ public MsalException(final Throwable throwable) { /** * Initializes a new instance of the exception class + * * @param message the error message that explains the reason for the exception */ public MsalException(final String message, String errorCode) { diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalInteractionRequiredException.java b/src/main/java/com/microsoft/aad/msal4j/MsalInteractionRequiredException.java index 98f3ad61..3730b1ab 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalInteractionRequiredException.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalInteractionRequiredException.java @@ -13,7 +13,7 @@ * This exception class is to inform developers that UI interaction is required for authentication * to succeed. */ -public class MsalInteractionRequiredException extends MsalServiceException{ +public class MsalInteractionRequiredException extends MsalServiceException { /** * Reason for the MsalInteractionRequiredException, enabling you to do more actions or inform the @@ -25,12 +25,13 @@ public class MsalInteractionRequiredException extends MsalServiceException{ /** * Initializes a new instance of the exception class + * * @param errorResponse response object contain information about error returned by server - * @param headerMap http headers from the server response + * @param headerMap http headers from the server response */ public MsalInteractionRequiredException( ErrorResponse errorResponse, - Map> headerMap) { + Map> headerMap) { super(errorResponse, headerMap); reason = InteractionRequiredExceptionReason.fromSubErrorString(errorResponse.subError); diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java b/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java index e89a47f8..5123dec5 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalRequest.java @@ -24,7 +24,7 @@ abstract class MsalRequest { MsalRequest(AbstractClientApplicationBase clientApplicationBase, AbstractMsalAuthorizationGrant abstractMsalAuthorizationGrant, - RequestContext requestContext){ + RequestContext requestContext) { this.application = clientApplicationBase; this.msalAuthorizationGrant = abstractMsalAuthorizationGrant; diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalServiceException.java b/src/main/java/com/microsoft/aad/msal4j/MsalServiceException.java index 235a47ae..28a15d14 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalServiceException.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalServiceException.java @@ -51,16 +51,18 @@ public class MsalServiceException extends MsalException { /** * Initializes a new instance of the exception class with a specified error message + * * @param message the error message that explains the reason for the exception */ - public MsalServiceException(final String message, final String error){ + public MsalServiceException(final String message, final String error) { super(message, error); } /** * Initializes a new instance of the exception class + * * @param errorResponse response object contain information about error returned by server - * @param httpHeaders http headers from the server response + * @param httpHeaders http headers from the server response */ public MsalServiceException( final ErrorResponse errorResponse, @@ -78,9 +80,10 @@ public MsalServiceException( /** * Initializes a new instance of the exception class + * * @param discoveryResponse response object from instance discovery network call */ - public MsalServiceException(final AadInstanceDiscoveryResponse discoveryResponse){ + public MsalServiceException(final AadInstanceDiscoveryResponse discoveryResponse) { super(discoveryResponse.errorDescription(), discoveryResponse.error()); this.correlationId = discoveryResponse.correlationId(); diff --git a/src/main/java/com/microsoft/aad/msal4j/MsalThrottlingException.java b/src/main/java/com/microsoft/aad/msal4j/MsalThrottlingException.java index 87cace27..8ae7bcf3 100644 --- a/src/main/java/com/microsoft/aad/msal4j/MsalThrottlingException.java +++ b/src/main/java/com/microsoft/aad/msal4j/MsalThrottlingException.java @@ -18,6 +18,7 @@ public class MsalThrottlingException extends MsalServiceException { /** * Constructor for MsalThrottlingException class + * * @param retryInMs */ public MsalThrottlingException(long retryInMs) { diff --git a/src/main/java/com/microsoft/aad/msal4j/NamespaceContextImpl.java b/src/main/java/com/microsoft/aad/msal4j/NamespaceContextImpl.java index 32ca1085..54925ca5 100644 --- a/src/main/java/com/microsoft/aad/msal4j/NamespaceContextImpl.java +++ b/src/main/java/com/microsoft/aad/msal4j/NamespaceContextImpl.java @@ -12,6 +12,7 @@ class NamespaceContextImpl implements NamespaceContext { private final static Map PREF_MAP = new HashMap(); + static { PREF_MAP.put("wsdl", "http://schemas.xmlsoap.org/wsdl/"); PREF_MAP.put("sp", diff --git a/src/main/java/com/microsoft/aad/msal4j/OAuthAuthorizationGrant.java b/src/main/java/com/microsoft/aad/msal4j/OAuthAuthorizationGrant.java index 4fc937dd..9c9a9323 100644 --- a/src/main/java/com/microsoft/aad/msal4j/OAuthAuthorizationGrant.java +++ b/src/main/java/com/microsoft/aad/msal4j/OAuthAuthorizationGrant.java @@ -22,7 +22,7 @@ class OAuthAuthorizationGrant extends AbstractMsalAuthorizationGrant { this(grant, scopesSet != null ? String.join(" ", scopesSet) : null, claims); } - String addCommonScopes(String scopes){ + String addCommonScopes(String scopes) { Set allScopes = new HashSet<>( Arrays.asList(COMMON_SCOPES_PARAM.split(SCOPES_DELIMITER))); @@ -52,7 +52,7 @@ String addCommonScopes(String scopes){ this.scopes = allScopes; this.params.put(SCOPE_PARAM_NAME, Collections.singletonList(allScopes)); - if(extraParams != null){ + if (extraParams != null) { this.params.putAll(extraParams); } } @@ -60,7 +60,7 @@ String addCommonScopes(String scopes){ OAuthAuthorizationGrant(AuthorizationGrant grant, Map> params) { this.grant = grant; - if(params != null){ + if (params != null) { this.params.putAll(params); } } @@ -77,7 +77,7 @@ public Map> toParameters() { return Collections.unmodifiableMap(outParams); } - + AuthorizationGrant getAuthorizationGrant() { return this.grant; } diff --git a/src/main/java/com/microsoft/aad/msal4j/OAuthHttpRequest.java b/src/main/java/com/microsoft/aad/msal4j/OAuthHttpRequest.java index 6b1a9a43..18046bd4 100644 --- a/src/main/java/com/microsoft/aad/msal4j/OAuthHttpRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/OAuthHttpRequest.java @@ -53,7 +53,7 @@ public HTTPResponse send() throws IOException { return createOauthHttpResponseFromHttpResponse(httpResponse); } - private Map configureHttpHeaders(){ + private Map configureHttpHeaders() { Map httpHeaders = new HashMap<>(extraHeaderParams); httpHeaders.put("Content-Type", HTTPContentType.ApplicationURLEncoded.contentType); @@ -85,7 +85,7 @@ private HTTPResponse createOauthHttpResponseFromHttpResponse(IHttpResponse httpR try { String contentType = HttpUtils.headerValue(httpResponse.headers(), "Content-Type"); - if(!StringHelper.isBlank(contentType)){ + if (!StringHelper.isBlank(contentType)) { response.setContentType(contentType); } } catch (final ParseException e) { @@ -94,14 +94,14 @@ private HTTPResponse createOauthHttpResponseFromHttpResponse(IHttpResponse httpR } Map> headers = httpResponse.headers(); - for(Map.Entry> header: headers.entrySet()){ + for (Map.Entry> header : headers.entrySet()) { - if(StringHelper.isBlank(header.getKey())){ + if (StringHelper.isBlank(header.getKey())) { continue; } String headerValue = response.getHeaderValue(header.getKey()); - if(headerValue == null || StringHelper.isBlank(headerValue)){ + if (headerValue == null || StringHelper.isBlank(headerValue)) { response.setHeader(header.getKey(), header.getValue().toArray(new String[0])); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/OnBehalfOfParameters.java b/src/main/java/com/microsoft/aad/msal4j/OnBehalfOfParameters.java index d636efda..6c2ab217 100644 --- a/src/main/java/com/microsoft/aad/msal4j/OnBehalfOfParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/OnBehalfOfParameters.java @@ -14,7 +14,7 @@ /** * Object containing parameters for On-Behalf-Of flow. Can be used as parameter to * {@link ConfidentialClientApplication#acquireToken(OnBehalfOfParameters)} - * + *

* For more details, see https://aka.ms/msal4j-on-behalf-of */ @Builder @@ -53,7 +53,8 @@ private static OnBehalfOfParametersBuilder builder() { /** * Builder for {@link OnBehalfOfParameters} - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param userAssertion {@link UserAssertion} created from access token received * @return builder that can be used to construct OnBehalfOfParameters */ diff --git a/src/main/java/com/microsoft/aad/msal4j/OpenBrowserAction.java b/src/main/java/com/microsoft/aad/msal4j/OpenBrowserAction.java index ee558227..8512e7c8 100644 --- a/src/main/java/com/microsoft/aad/msal4j/OpenBrowserAction.java +++ b/src/main/java/com/microsoft/aad/msal4j/OpenBrowserAction.java @@ -15,6 +15,7 @@ public interface OpenBrowserAction { * Override for providing custom browser initialization logic. Method that is called by MSAL * when doing {@link IPublicClientApplication#acquireToken(InteractiveRequestParameters)}. If * not overridden, MSAL will attempt to open URL in default system browser. + * * @param url URL to the /authorize endpoint which should opened up in a browser so the user can * provide their credentials and consent to scopes. */ diff --git a/src/main/java/com/microsoft/aad/msal4j/Prompt.java b/src/main/java/com/microsoft/aad/msal4j/Prompt.java index f4315e95..19e37aa4 100644 --- a/src/main/java/com/microsoft/aad/msal4j/Prompt.java +++ b/src/main/java/com/microsoft/aad/msal4j/Prompt.java @@ -11,41 +11,41 @@ public enum Prompt { /** * The user should be prompted to reauthenticate. */ - LOGIN ("login"), + LOGIN("login"), /** - *The user is prompted to select an account, interrupting single sign on. The user may select + * The user is prompted to select an account, interrupting single sign on. The user may select * an existing signed-in account, enter their credentials for a remembered account, * or choose to use a different account altogether. */ - SELECT_ACCOUNT ("select_account"), + SELECT_ACCOUNT("select_account"), /** * User consent has been granted, but needs to be updated. The user should be prompted to consent. */ - CONSENT ("consent"), + CONSENT("consent"), /** * An administrator should be prompted to consent on behalf of all users in their organization. - * + *

* Deprecated, instead use Prompt.ADMIN_CONSENT */ @Deprecated - ADMING_CONSENT ("admin_consent"), + ADMING_CONSENT("admin_consent"), /** * An administrator should be prompted to consent on behalf of all users in their organization. */ - ADMIN_CONSENT ("admin_consent"); + ADMIN_CONSENT("admin_consent"); private String prompt; - Prompt(String prompt){ + Prompt(String prompt) { this.prompt = prompt; } @Override - public String toString(){ + public String toString() { return prompt; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/PublicApi.java b/src/main/java/com/microsoft/aad/msal4j/PublicApi.java index 2df5c75a..e5c14fc7 100644 --- a/src/main/java/com/microsoft/aad/msal4j/PublicApi.java +++ b/src/main/java/com/microsoft/aad/msal4j/PublicApi.java @@ -19,11 +19,11 @@ enum PublicApi { private final int apiId; - PublicApi(int apiId){ + PublicApi(int apiId) { this.apiId = apiId; } - int getApiId(){ + int getApiId() { return apiId; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenCacheEntity.java b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenCacheEntity.java index cd9be21e..8a16262b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenCacheEntity.java +++ b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenCacheEntity.java @@ -22,21 +22,20 @@ class RefreshTokenCacheEntity extends Credential { @JsonProperty("family_id") private String family_id; - boolean isFamilyRT(){ + boolean isFamilyRT() { return !StringHelper.isBlank(family_id); } - String getKey(){ + String getKey() { List keyParts = new ArrayList<>(); keyParts.add(homeAccountId); keyParts.add(environment); keyParts.add(credentialType); - if(isFamilyRT()){ + if (isFamilyRT()) { keyParts.add(family_id); - } - else{ + } else { keyParts.add(clientId); } diff --git a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenParameters.java b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenParameters.java index e4bcb43c..8237e45b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenParameters.java @@ -16,9 +16,9 @@ * Object containing parameters for refresh token request. Can be used as parameter to * {@link PublicClientApplication#acquireToken(RefreshTokenParameters)} or to * {@link ConfidentialClientApplication#acquireToken(RefreshTokenParameters)} - * - * RefreshTokenParameters should only be used for migration scenarios (when moving from ADAL to - * MSAL). To acquire tokens silently, use {@link AbstractClientApplicationBase#acquireTokenSilently(SilentParameters)} + *

+ * RefreshTokenParameters should only be used for migration scenarios (when moving from ADAL to + * MSAL). To acquire tokens silently, use {@link AbstractClientApplicationBase#acquireTokenSilently(SilentParameters)} */ @Builder @Accessors(fluent = true) @@ -55,12 +55,13 @@ private static RefreshTokenParametersBuilder builder() { /** * Builder for {@link RefreshTokenParameters} - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param refreshToken refresh token received form the STS * @return builder object that can be used to construct {@link RefreshTokenParameters} */ public static RefreshTokenParametersBuilder builder(Set scopes, String refreshToken) { - + validateNotBlank("refreshToken", refreshToken); return builder() diff --git a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java index 551b5bae..3e354900 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/RefreshTokenRequest.java @@ -47,7 +47,7 @@ String getFullThumbprint() { ? parentSilentRequest.requestAuthority().authority() : application().authority(); sb.append(authority + POINT_DELIMITER); - if(parentSilentRequest != null && parentSilentRequest.parameters().account() != null){ + if (parentSilentRequest != null && parentSilentRequest.parameters().account() != null) { sb.append(parentSilentRequest.parameters().account().homeAccountId() + POINT_DELIMITER); } diff --git a/src/main/java/com/microsoft/aad/msal4j/RegionTelemetry.java b/src/main/java/com/microsoft/aad/msal4j/RegionTelemetry.java index ec1c029c..aae89496 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RegionTelemetry.java +++ b/src/main/java/com/microsoft/aad/msal4j/RegionTelemetry.java @@ -18,7 +18,7 @@ enum RegionTelemetry { /** * These values represent the result of the attempt to find region info * Three values cover cases where developer provided a region and either it matches the autodetected region (1), - * autodetection failed (2), or the autodetected region does not match the developer provided region (3) + * autodetection failed (2), or the autodetected region does not match the developer provided region (3) * Two values cover cases where developer just requested autodetection, and we either detected the region (4) or failed (5) */ REGION_OUTCOME_DEVELOPER_AUTODETECT_MATCH(1), @@ -29,7 +29,7 @@ enum RegionTelemetry { final int telemetryValue; - RegionTelemetry(int telemetryValue){ + RegionTelemetry(int telemetryValue) { this.telemetryValue = telemetryValue; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/RequestedClaim.java b/src/main/java/com/microsoft/aad/msal4j/RequestedClaim.java index 075baf29..2d9f9640 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RequestedClaim.java +++ b/src/main/java/com/microsoft/aad/msal4j/RequestedClaim.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; + import java.util.Collections; import java.util.Map; diff --git a/src/main/java/com/microsoft/aad/msal4j/RequestedClaimAdditionalInfo.java b/src/main/java/com/microsoft/aad/msal4j/RequestedClaimAdditionalInfo.java index 7b8c0b3a..83bcd023 100644 --- a/src/main/java/com/microsoft/aad/msal4j/RequestedClaimAdditionalInfo.java +++ b/src/main/java/com/microsoft/aad/msal4j/RequestedClaimAdditionalInfo.java @@ -8,6 +8,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; + import java.util.List; /** diff --git a/src/main/java/com/microsoft/aad/msal4j/ResponseMode.java b/src/main/java/com/microsoft/aad/msal4j/ResponseMode.java index 43767bc0..9f24d2e7 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ResponseMode.java +++ b/src/main/java/com/microsoft/aad/msal4j/ResponseMode.java @@ -29,12 +29,12 @@ public enum ResponseMode { private String responseMode; - ResponseMode(String responseMode){ + ResponseMode(String responseMode) { this.responseMode = responseMode; } @Override - public String toString(){ + public String toString() { return this.responseMode; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/SAML11BearerGrant.java b/src/main/java/com/microsoft/aad/msal4j/SAML11BearerGrant.java index 9ec71197..54f10d49 100644 --- a/src/main/java/com/microsoft/aad/msal4j/SAML11BearerGrant.java +++ b/src/main/java/com/microsoft/aad/msal4j/SAML11BearerGrant.java @@ -27,7 +27,7 @@ public SAML11BearerGrant(Base64URL assertion) { public Map> toParameters() { Map> params = super.toParameters(); - params.put("grant_type",Collections.singletonList(grantType.getValue())); + params.put("grant_type", Collections.singletonList(grantType.getValue())); return params; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/SafeDocumentBuilderFactory.java b/src/main/java/com/microsoft/aad/msal4j/SafeDocumentBuilderFactory.java index 173c9331..5db74259 100644 --- a/src/main/java/com/microsoft/aad/msal4j/SafeDocumentBuilderFactory.java +++ b/src/main/java/com/microsoft/aad/msal4j/SafeDocumentBuilderFactory.java @@ -8,7 +8,7 @@ final class SafeDocumentBuilderFactory { - public static DocumentBuilderFactory createInstance() throws ParserConfigurationException{ + public static DocumentBuilderFactory createInstance() throws ParserConfigurationException { final DocumentBuilderFactory builderFactory = DocumentBuilderFactory .newInstance(); @@ -27,9 +27,9 @@ public static DocumentBuilderFactory createInstance() throws ParserConfiguration builderFactory.setXIncludeAware(false); builderFactory.setExpandEntityReferences(false); - + builderFactory.setNamespaceAware(true); return builderFactory; } - + } diff --git a/src/main/java/com/microsoft/aad/msal4j/ServiceBundle.java b/src/main/java/com/microsoft/aad/msal4j/ServiceBundle.java index 704544e1..58111ea9 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ServiceBundle.java +++ b/src/main/java/com/microsoft/aad/msal4j/ServiceBundle.java @@ -13,7 +13,7 @@ class ServiceBundle { private ServerSideTelemetry serverSideTelemetry; ServiceBundle(ExecutorService executorService, IHttpClient httpClient, - TelemetryManager telemetryManager){ + TelemetryManager telemetryManager) { this.executorService = executorService; this.telemetryManager = telemetryManager; this.httpClient = httpClient; @@ -25,15 +25,15 @@ ExecutorService getExecutorService() { return executorService; } - TelemetryManager getTelemetryManager(){ + TelemetryManager getTelemetryManager() { return telemetryManager; } - IHttpClient getHttpClient(){ + IHttpClient getHttpClient() { return httpClient; } - ServerSideTelemetry getServerSideTelemetry(){ + ServerSideTelemetry getServerSideTelemetry() { return serverSideTelemetry; } } \ No newline at end of file diff --git a/src/main/java/com/microsoft/aad/msal4j/SilentParameters.java b/src/main/java/com/microsoft/aad/msal4j/SilentParameters.java index 6547e438..3c0da8ca 100644 --- a/src/main/java/com/microsoft/aad/msal4j/SilentParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/SilentParameters.java @@ -16,7 +16,6 @@ * Object containing parameters for silent requests. Can be used as parameter to * {@link PublicClientApplication#acquireTokenSilently(SilentParameters)} or to * {@link ConfidentialClientApplication#acquireTokenSilently(SilentParameters)} - * */ @Builder @Accessors(fluent = true) @@ -62,7 +61,8 @@ private static SilentParametersBuilder builder() { /** * Builder for SilentParameters - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param account {@link IAccount} for which to acquire a token for * @return builder object that can be used to construct SilentParameters */ @@ -79,12 +79,11 @@ public static SilentParametersBuilder builder(Set scopes, IAccount accou /** * Builder for SilentParameters * + * @param scopes scopes application is requesting access to + * @return builder object that can be used to construct SilentParameters * @deprecated This method was used for using cached tokens in client credentials or On-behalf-of * flow. Those flows will now by default attempt to use cached the cached tokens, so there is * no need to call acquireTokenSilently. This overload will be removed in the next major version. - * - * @param scopes scopes application is requesting access to - * @return builder object that can be used to construct SilentParameters */ @Deprecated public static SilentParametersBuilder builder(Set scopes) { diff --git a/src/main/java/com/microsoft/aad/msal4j/SystemBrowserOptions.java b/src/main/java/com/microsoft/aad/msal4j/SystemBrowserOptions.java index 00e47a78..52c3dbd3 100644 --- a/src/main/java/com/microsoft/aad/msal4j/SystemBrowserOptions.java +++ b/src/main/java/com/microsoft/aad/msal4j/SystemBrowserOptions.java @@ -13,9 +13,9 @@ /** * Options for using the default OS browser as a separate process to handle interactive authentication. - * MSAL will listen for the OS browser to finish authenticating, but it cannot close the browser. - * It can however response with a HTTP 200 OK message or a 302 Redirect, which can be configured here. - * For more details, see https://aka.ms/msal4j-interactive-request + * MSAL will listen for the OS browser to finish authenticating, but it cannot close the browser. + * It can however response with a HTTP 200 OK message or a 302 Redirect, which can be configured here. + * For more details, see https://aka.ms/msal4j-interactive-request */ @Builder @Accessors(fluent = true) diff --git a/src/main/java/com/microsoft/aad/msal4j/TelemetryHelper.java b/src/main/java/com/microsoft/aad/msal4j/TelemetryHelper.java index d24ada87..3c5f5a20 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TelemetryHelper.java +++ b/src/main/java/com/microsoft/aad/msal4j/TelemetryHelper.java @@ -3,7 +3,7 @@ package com.microsoft.aad.msal4j; -class TelemetryHelper implements AutoCloseable{ +class TelemetryHelper implements AutoCloseable { private Event eventToEnd; private String requestId; private String clientId; @@ -22,15 +22,15 @@ class TelemetryHelper implements AutoCloseable{ this.eventToEnd = event; this.shouldFlush = shouldFlush; - if(telemetry != null){ + if (telemetry != null) { telemetry.startEvent(requestId, event); } } - public void close(){ - if(telemetry != null) { + public void close() { + if (telemetry != null) { telemetry.stopEvent(requestId, eventToEnd); - if(shouldFlush){ + if (shouldFlush) { telemetry.flush(requestId, clientId); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/TelemetryManager.java b/src/main/java/com/microsoft/aad/msal4j/TelemetryManager.java index 2a0493ec..613b8dde 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TelemetryManager.java +++ b/src/main/java/com/microsoft/aad/msal4j/TelemetryManager.java @@ -15,7 +15,7 @@ import java.util.function.Consumer; import java.util.function.Predicate; -class TelemetryManager implements ITelemetryManager, ITelemetry{ +class TelemetryManager implements ITelemetryManager, ITelemetry { private final ConcurrentHashMap> completedEvents = new ConcurrentHashMap<>(); private final ConcurrentHashMap eventsInProgress = new ConcurrentHashMap<>(); @@ -23,51 +23,51 @@ class TelemetryManager implements ITelemetryManager, ITelemetry{ new ConcurrentHashMap<>(); private boolean onlySendFailureTelemetry; - private Consumer>> telemetryConsumer; + private Consumer>> telemetryConsumer; - public TelemetryManager(Consumer>> telemetryConsumer, - boolean onlySendFailureTelemetry){ - this.telemetryConsumer= telemetryConsumer; + public TelemetryManager(Consumer>> telemetryConsumer, + boolean onlySendFailureTelemetry) { + this.telemetryConsumer = telemetryConsumer; this.onlySendFailureTelemetry = onlySendFailureTelemetry; } public TelemetryHelper createTelemetryHelper(String requestId, String clientId, Event eventToStart, - Boolean shouldFlush){ + Boolean shouldFlush) { return new TelemetryHelper(this, requestId, clientId, eventToStart, shouldFlush); } - public String generateRequestId(){ + public String generateRequestId() { return UUID.randomUUID().toString(); } @Override public void startEvent(String requestId, Event eventToStart) { - if(hasConsumer() && !StringHelper.isBlank(requestId)){ + if (hasConsumer() && !StringHelper.isBlank(requestId)) { eventsInProgress.put(new EventKey(requestId, eventToStart), eventToStart); } } @Override - public void stopEvent(String requestId, Event eventToStop){ - if(!hasConsumer() || StringHelper.isBlank(requestId)) return; + public void stopEvent(String requestId, Event eventToStop) { + if (!hasConsumer() || StringHelper.isBlank(requestId)) return; EventKey eventKey = new EventKey(requestId, eventToStop); Event eventStarted = eventsInProgress.getOrDefault(eventKey, null); - if(eventStarted == null){ + if (eventStarted == null) { return; } eventToStop.stop(); incrementEventCount(requestId, eventToStop); - if(!completedEvents.containsKey(requestId)){ + if (!completedEvents.containsKey(requestId)) { List eventList = new ArrayList<>(Arrays.asList(eventToStop)); completedEvents.put(requestId, eventList); } else { - List eventList = completedEvents.get(requestId); + List eventList = completedEvents.get(requestId); eventList.add(eventToStop); } @@ -75,12 +75,12 @@ public void stopEvent(String requestId, Event eventToStop){ } @Override - public void flush(String requestId, String clientId){ - if(!hasConsumer()){ + public void flush(String requestId, String clientId) { + if (!hasConsumer()) { return; } - if(!completedEvents.containsKey(requestId)){ + if (!completedEvents.containsKey(requestId)) { return; } completedEvents.get(requestId).addAll(collateOrphanedEvents(requestId)); @@ -93,10 +93,10 @@ public void flush(String requestId, String clientId){ Predicate isSuccessfulPredicate = event -> event instanceof ApiEvent && ((ApiEvent) event).getWasSuccessful(); - if(onlySendFailureTelemetry && eventsToFlush.stream().anyMatch(isSuccessfulPredicate)){ + if (onlySendFailureTelemetry && eventsToFlush.stream().anyMatch(isSuccessfulPredicate)) { eventsToFlush.clear(); } - if(eventsToFlush.size() <= 0){ + if (eventsToFlush.size() <= 0) { return; } eventsToFlush.add(0, new DefaultEvent(clientId, eventCountToFlush)); @@ -104,28 +104,30 @@ public void flush(String requestId, String clientId){ telemetryConsumer.accept(Collections.unmodifiableList(eventsToFlush)); } - private Collection collateOrphanedEvents(String requestId){ + private Collection collateOrphanedEvents(String requestId) { List orphanedEvents = new ArrayList<>(); - for(EventKey key: eventsInProgress.keySet()){ - if(key.getRequestId().equalsIgnoreCase(requestId)){ + for (EventKey key : eventsInProgress.keySet()) { + if (key.getRequestId().equalsIgnoreCase(requestId)) { orphanedEvents.add(eventsInProgress.remove(key)); } } return orphanedEvents; } - private void incrementEventCount(String requestId, Event eventToIncrement){ + private void incrementEventCount(String requestId, Event eventToIncrement) { String eventName = eventToIncrement.get(Event.EVENT_NAME_KEY); ConcurrentHashMap eventNameCount = eventCount.getOrDefault( - requestId, new ConcurrentHashMap(){ - { put(eventName, 0); } + requestId, new ConcurrentHashMap() { + { + put(eventName, 0); + } }); eventNameCount.put(eventName, eventNameCount.getOrDefault(eventName, 0) + 1); - eventCount.put(requestId,eventNameCount); + eventCount.put(requestId, eventNameCount); } - private boolean hasConsumer(){ + private boolean hasConsumer() { return telemetryConsumer != null; } } diff --git a/src/main/java/com/microsoft/aad/msal4j/TenantProfile.java b/src/main/java/com/microsoft/aad/msal4j/TenantProfile.java index 7a22c35a..98011ee1 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TenantProfile.java +++ b/src/main/java/com/microsoft/aad/msal4j/TenantProfile.java @@ -7,6 +7,7 @@ import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; + import java.util.Map; /** diff --git a/src/main/java/com/microsoft/aad/msal4j/ThrottlingCache.java b/src/main/java/com/microsoft/aad/msal4j/ThrottlingCache.java index fbe1e21c..89e1f348 100644 --- a/src/main/java/com/microsoft/aad/msal4j/ThrottlingCache.java +++ b/src/main/java/com/microsoft/aad/msal4j/ThrottlingCache.java @@ -41,11 +41,8 @@ static long retryInMs(String requestHash) { } private static boolean isCacheEntryValid(long currentTimestamp, long expirationTimestamp) { - if (currentTimestamp < expirationTimestamp && - currentTimestamp >= expirationTimestamp - MAX_THROTTLING_TIME_SEC * 1000) { - return true; - } - return false; + return currentTimestamp < expirationTimestamp && + currentTimestamp >= expirationTimestamp - MAX_THROTTLING_TIME_SEC * 1000; } private static void removeInvalidCacheEntities() { diff --git a/src/main/java/com/microsoft/aad/msal4j/TokenCache.java b/src/main/java/com/microsoft/aad/msal4j/TokenCache.java index f991ef6c..51e47329 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TokenCache.java +++ b/src/main/java/com/microsoft/aad/msal4j/TokenCache.java @@ -18,7 +18,7 @@ /** * Cache used for storing tokens. For more details, see https://aka.ms/msal4j-token-cache - * + *

* Conditionally thread-safe */ public class TokenCache implements ITokenCache { @@ -98,7 +98,7 @@ private static void mergeUpdates(JsonNode old, JsonNode update) { if (!old.has(uKey)) { if (!uValue.isNull() && !(uValue.isObject() && uValue.size() == 0)) { - ((ObjectNode)old).set(uKey, uValue); + ((ObjectNode) old).set(uKey, uValue); } } // merge old and new property @@ -107,7 +107,7 @@ private static void mergeUpdates(JsonNode old, JsonNode update) { if (uValue.isObject()) { mergeUpdates(oValue, uValue); } else { - ((ObjectNode)old).set(uKey, uValue); + ((ObjectNode) old).set(uKey, uValue); } } } @@ -148,10 +148,9 @@ public String serialize() { return JsonHelper.mapper.writeValueAsString(cache); } return JsonHelper.mapper.writeValueAsString(this); - } - catch (IOException e) { + } catch (IOException e) { throw new MsalClientException(e); - }finally { + } finally { lock.readLock().unlock(); } } @@ -231,7 +230,7 @@ private static RefreshTokenCacheEntity createRefreshTokenCacheEntity(TokenReques rt.clientId(tokenRequestExecutor.getMsalRequest().application().clientId()); rt.secret(authenticationResult.refreshToken()); - if(tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest){ + if (tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest) { OnBehalfOfRequest onBehalfOfRequest = (OnBehalfOfRequest) tokenRequestExecutor.getMsalRequest(); rt.userAssertionHash(onBehalfOfRequest.parameters.userAssertion().getAssertionHash()); } @@ -258,7 +257,7 @@ private static AccessTokenCacheEntity createAccessTokenCacheEntity(TokenRequestE at.target(scopes); - if(tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest){ + if (tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest) { OnBehalfOfRequest onBehalfOfRequest = (OnBehalfOfRequest) tokenRequestExecutor.getMsalRequest(); at.userAssertionHash(onBehalfOfRequest.parameters.userAssertion().getAssertionHash()); } @@ -266,7 +265,7 @@ private static AccessTokenCacheEntity createAccessTokenCacheEntity(TokenRequestE long currTimestampSec = System.currentTimeMillis() / 1000; at.cachedAt(Long.toString(currTimestampSec)); at.expiresOn(Long.toString(authenticationResult.expiresOn())); - if(authenticationResult.refreshOn() > 0 ){ + if (authenticationResult.refreshOn() > 0) { at.refreshOn(Long.toString(authenticationResult.refreshOn())); } if (authenticationResult.extExpiresOn() > 0) { @@ -290,7 +289,7 @@ private static IdTokenCacheEntity createIdTokenCacheEntity(TokenRequestExecutor idToken.secret(authenticationResult.idToken()); idToken.realm(tokenRequestExecutor.requestAuthority.tenant()); - if(tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest){ + if (tokenRequestExecutor.getMsalRequest() instanceof OnBehalfOfRequest) { OnBehalfOfRequest onBehalfOfRequest = (OnBehalfOfRequest) tokenRequestExecutor.getMsalRequest(); idToken.userAssertionHash(onBehalfOfRequest.parameters.userAssertion().getAssertionHash()); } @@ -341,7 +340,7 @@ Set getAccounts(String clientId) { rootAccounts.put(accCached.homeAccountId(), acc); } - if(profile != null) { + if (profile != null) { ((Account) rootAccounts.get(accCached.homeAccountId())).tenantProfiles.put(accCached.realm(), profile); } @@ -401,8 +400,8 @@ private Set getFamilyClientIds(String familyId, Set environmentA /** * Remove all cache entities related to account, including account cache entity * - * @param clientId client id - * @param account account + * @param clientId client id + * @param account account */ void removeAccount(String clientId, IAccount account) { try (CacheAspect cacheAspect = new CacheAspect( @@ -450,7 +449,7 @@ private boolean isMatchingScopes(AccessTokenCacheEntity accessTokenCacheEntity, } private boolean userAssertionHashMatches(Credential credential, String userAssertionHash) { - if(userAssertionHash == null) { + if (userAssertionHash == null) { return true; } @@ -459,7 +458,7 @@ private boolean userAssertionHashMatches(Credential credential, String userAsser } private boolean userAssertionHashMatches(AccountCacheEntity accountCacheEntity, String userAssertionHash) { - if(userAssertionHash == null) { + if (userAssertionHash == null) { return true; } @@ -478,12 +477,12 @@ private Optional getAccessTokenCacheEntity( return accessTokens.values().stream().filter( accessToken -> accessToken.homeAccountId.equals(account.homeAccountId()) && - environmentAliases.contains(accessToken.environment) && - Long.parseLong(accessToken.expiresOn()) > currTimeStampSec + MIN_ACCESS_TOKEN_EXPIRE_IN_SEC && - accessToken.realm.equals(authority.tenant()) && - accessToken.clientId.equals(clientId) && - isMatchingScopes(accessToken, scopes) - ).findAny(); + environmentAliases.contains(accessToken.environment) && + Long.parseLong(accessToken.expiresOn()) > currTimeStampSec + MIN_ACCESS_TOKEN_EXPIRE_IN_SEC && + accessToken.realm.equals(authority.tenant()) && + accessToken.clientId.equals(clientId) && + isMatchingScopes(accessToken, scopes) + ).findAny(); } private Optional getApplicationAccessTokenCacheEntity( @@ -497,11 +496,11 @@ private Optional getApplicationAccessTokenCacheEntity( return accessTokens.values().stream().filter( accessToken -> userAssertionHashMatches(accessToken, userAssertionHash) && - environmentAliases.contains(accessToken.environment) && - Long.parseLong(accessToken.expiresOn()) > currTimeStampSec + MIN_ACCESS_TOKEN_EXPIRE_IN_SEC && - accessToken.realm.equals(authority.tenant()) && - accessToken.clientId.equals(clientId) && - isMatchingScopes(accessToken, scopes)) + environmentAliases.contains(accessToken.environment) && + Long.parseLong(accessToken.expiresOn()) > currTimeStampSec + MIN_ACCESS_TOKEN_EXPIRE_IN_SEC && + accessToken.realm.equals(authority.tenant()) && + accessToken.clientId.equals(clientId) && + isMatchingScopes(accessToken, scopes)) .findAny(); } @@ -514,10 +513,10 @@ private Optional getIdTokenCacheEntity( return idTokens.values().stream().filter( idToken -> idToken.homeAccountId.equals(account.homeAccountId()) && - environmentAliases.contains(idToken.environment) && - idToken.realm.equals(authority.tenant()) && - idToken.clientId.equals(clientId) - ).findAny(); + environmentAliases.contains(idToken.environment) && + idToken.realm.equals(authority.tenant()) && + idToken.clientId.equals(clientId) + ).findAny(); } private Optional getIdTokenCacheEntity( @@ -542,9 +541,9 @@ private Optional getRefreshTokenCacheEntity( return refreshTokens.values().stream().filter( refreshToken -> refreshToken.homeAccountId.equals(account.homeAccountId()) && - environmentAliases.contains(refreshToken.environment) && - refreshToken.clientId.equals(clientId) - ).findAny(); + environmentAliases.contains(refreshToken.environment) && + refreshToken.clientId.equals(clientId) + ).findAny(); } private Optional getAccountCacheEntity( @@ -554,8 +553,8 @@ private Optional getAccountCacheEntity( return accounts.values().stream().filter( acc -> acc.homeAccountId.equals(account.homeAccountId()) && - environmentAliases.contains(acc.environment) - ).findAny(); + environmentAliases.contains(acc.environment) + ).findAny(); } private Optional getAccountCacheEntity( @@ -565,7 +564,7 @@ private Optional getAccountCacheEntity( return accounts.values().stream().filter( acc -> userAssertionHashMatches(acc, userAssertionHash) && environmentAliases.contains(acc.environment) - ).findAny(); + ).findAny(); } private Optional getAnyFamilyRefreshTokenCacheEntity @@ -625,7 +624,7 @@ AuthenticationResult getCachedAuthenticationResult( builder. accessToken(atCacheEntity.get().secret). expiresOn(Long.parseLong(atCacheEntity.get().expiresOn())); - if(atCacheEntity.get().refreshOn() != null){ + if (atCacheEntity.get().refreshOn() != null) { builder.refreshOn(Long.parseLong(atCacheEntity.get().refreshOn())); } } @@ -673,7 +672,7 @@ AuthenticationResult getCachedAuthenticationResult( builder. accessToken(atCacheEntity.get().secret). expiresOn(Long.parseLong(atCacheEntity.get().expiresOn())); - if(atCacheEntity.get().refreshOn() != null){ + if (atCacheEntity.get().refreshOn() != null) { builder.refreshOn(Long.parseLong(atCacheEntity.get().refreshOn())); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/TokenCacheAccessContext.java b/src/main/java/com/microsoft/aad/msal4j/TokenCacheAccessContext.java index 3a0d4a2a..b78523a5 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TokenCacheAccessContext.java +++ b/src/main/java/com/microsoft/aad/msal4j/TokenCacheAccessContext.java @@ -9,7 +9,7 @@ /** * Context in which the the token cache is accessed - * + *

* For more details, see https://aka.ms/msal4j-token-cache */ @Builder diff --git a/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java b/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java index dd046e90..3230fc00 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java +++ b/src/main/java/com/microsoft/aad/msal4j/TokenRequestExecutor.java @@ -79,7 +79,7 @@ OAuthHttpRequest createOauthHttpRequest() throws SerializeException, MalformedUR } private AuthenticationResult createAuthenticationResultFromOauthHttpResponse( - HTTPResponse oauthHttpResponse) throws ParseException{ + HTTPResponse oauthHttpResponse) throws ParseException { AuthenticationResult result; if (oauthHttpResponse.getStatusCode() == HTTPResponse.SC_OK) { @@ -99,7 +99,7 @@ private AuthenticationResult createAuthenticationResultFromOauthHttpResponse( AuthorityType type = msalRequest.application().authenticationAuthority.authorityType; if (!StringHelper.isBlank(response.getClientInfo())) { - if(type == AuthorityType.B2C){ + if (type == AuthorityType.B2C) { B2CAuthority authority = (B2CAuthority) msalRequest.application().authenticationAuthority; accountCacheEntity = AccountCacheEntity.create( response.getClientInfo(), @@ -112,8 +112,7 @@ private AuthenticationResult createAuthenticationResultFromOauthHttpResponse( requestAuthority, idToken); } - } - else if(type == AuthorityType.ADFS){ + } else if (type == AuthorityType.ADFS) { accountCacheEntity = AccountCacheEntity.createADFSAccount(requestAuthority, idToken); } } @@ -134,7 +133,7 @@ else if(type == AuthorityType.ADFS){ } else { // http codes indicating that STS did not log request - if(oauthHttpResponse.getStatusCode() == HttpHelper.HTTP_STATUS_429 || oauthHttpResponse.getStatusCode() >= HttpHelper.HTTP_STATUS_500){ + if (oauthHttpResponse.getStatusCode() == HttpHelper.HTTP_STATUS_429 || oauthHttpResponse.getStatusCode() >= HttpHelper.HTTP_STATUS_500) { serviceBundle.getServerSideTelemetry().previousRequests.putAll( serviceBundle.getServerSideTelemetry().previousRequestInProgress); } diff --git a/src/main/java/com/microsoft/aad/msal4j/TokenResponse.java b/src/main/java/com/microsoft/aad/msal4j/TokenResponse.java index 78c0e5fc..1706ce9c 100644 --- a/src/main/java/com/microsoft/aad/msal4j/TokenResponse.java +++ b/src/main/java/com/microsoft/aad/msal4j/TokenResponse.java @@ -48,11 +48,9 @@ static TokenResponse parseHttpResponse(final HTTPResponse httpResponse) throws P static Long getLongValue(JSONObject jsonObject, String key) throws ParseException { Object value = jsonObject.get(key); - if(value instanceof Long){ + if (value instanceof Long) { return JSONObjectUtils.getLong(jsonObject, key); - } - else - { + } else { return Long.parseLong(JSONObjectUtils.getString(jsonObject, key)); } } diff --git a/src/main/java/com/microsoft/aad/msal4j/UserAssertion.java b/src/main/java/com/microsoft/aad/msal4j/UserAssertion.java index 1347a3a7..f158dc2b 100644 --- a/src/main/java/com/microsoft/aad/msal4j/UserAssertion.java +++ b/src/main/java/com/microsoft/aad/msal4j/UserAssertion.java @@ -16,8 +16,7 @@ public class UserAssertion implements IUserAssertion { * Constructor to create credential with a jwt token encoded as a base64 url * encoded string. * - * @param assertion - * The jwt used as credential. + * @param assertion The jwt used as credential. */ public UserAssertion(final String assertion) { if (StringHelper.isBlank(assertion)) { diff --git a/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordParameters.java b/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordParameters.java index 38532f24..c409244a 100644 --- a/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordParameters.java +++ b/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordParameters.java @@ -15,7 +15,7 @@ /** * Object containing parameters for Username/Password flow. Can be used as parameter to * {@link PublicClientApplication#acquireToken(UserNamePasswordParameters)} - * + *

* For more details, see https://aka.ms/msal4j-username-password */ @Builder @@ -52,7 +52,7 @@ public class UserNamePasswordParameters implements IAcquireTokenParameters { */ private Map extraHttpHeaders; - public char[] password(){ + public char[] password() { return password.clone(); } @@ -63,13 +63,14 @@ private static UserNamePasswordParametersBuilder builder() { /** * Builder for UserNameParameters - * @param scopes scopes application is requesting access to + * + * @param scopes scopes application is requesting access to * @param username username of the account * @param password char array containing credentials for the username * @return builder object that can be used to construct UserNameParameters */ public static UserNamePasswordParametersBuilder builder - (Set scopes, String username, char[] password) { + (Set scopes, String username, char[] password) { validateNotEmpty("scopes", scopes); validateNotBlank("username", username); @@ -81,7 +82,7 @@ private static UserNamePasswordParametersBuilder builder() { .password(password); } - public static class UserNamePasswordParametersBuilder{ + public static class UserNamePasswordParametersBuilder { public UserNamePasswordParametersBuilder password(char[] password) { this.password = password.clone(); return this; diff --git a/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordRequest.java b/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordRequest.java index b9aa8bad..a3870dd9 100644 --- a/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/UserNamePasswordRequest.java @@ -6,7 +6,7 @@ import com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant; import com.nimbusds.oauth2.sdk.auth.Secret; -class UserNamePasswordRequest extends MsalRequest{ +class UserNamePasswordRequest extends MsalRequest { UserNamePasswordRequest(UserNamePasswordParameters parameters, PublicClientApplication application, diff --git a/src/main/java/com/microsoft/aad/msal4j/WSTrustRequest.java b/src/main/java/com/microsoft/aad/msal4j/WSTrustRequest.java index 2d90c8a7..1f4decf6 100644 --- a/src/main/java/com/microsoft/aad/msal4j/WSTrustRequest.java +++ b/src/main/java/com/microsoft/aad/msal4j/WSTrustRequest.java @@ -43,7 +43,7 @@ static WSTrustResponse execute(String username, policy.getVersion(), cloudAudienceUrn).toString(); HttpRequest httpRequest = new HttpRequest(HttpMethod.POST, policy.getUrl(), headers, body); - IHttpResponse response = HttpHelper.executeHttpRequest(httpRequest, requestContext , serviceBundle); + IHttpResponse response = HttpHelper.executeHttpRequest(httpRequest, requestContext, serviceBundle); return WSTrustResponse.parse(response.body(), policy.getVersion()); } @@ -65,7 +65,7 @@ static WSTrustResponse execute(String url, BindingPolicy policy = MexParser.getWsTrustEndpointFromMexResponse(mexResponse.body(), logPii); - if(policy == null){ + if (policy == null) { throw new MsalServiceException( "WsTrust endpoint not found in metadata document", AuthenticationErrorCode.WSTRUST_ENDPOINT_NOT_FOUND_IN_METADATA_DOCUMENT); @@ -81,11 +81,11 @@ static WSTrustResponse execute(String mexURL, boolean logPii) throws Exception { HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, mexURL); - IHttpResponse mexResponse = HttpHelper.executeHttpRequest(httpRequest, requestContext,serviceBundle); + IHttpResponse mexResponse = HttpHelper.executeHttpRequest(httpRequest, requestContext, serviceBundle); BindingPolicy policy = MexParser.getPolicyFromMexResponseForIntegrated(mexResponse.body(), logPii); - if(policy == null){ + if (policy == null) { throw new MsalServiceException("WsTrust endpoint not found in metadata document", AuthenticationErrorCode.WSTRUST_ENDPOINT_NOT_FOUND_IN_METADATA_DOCUMENT); } @@ -188,10 +188,10 @@ static StringBuilder buildMessage(String address, String username, return messageBuilder; } - static String escapeXMLElementData(String data){ + static String escapeXMLElementData(String data) { StringBuilder sb = new StringBuilder(); - for(char ch : data.toCharArray()){ - switch (ch){ + for (char ch : data.toCharArray()) { + switch (ch) { case '<': sb.append("<"); break; diff --git a/src/main/java/com/microsoft/aad/msal4j/WSTrustResponse.java b/src/main/java/com/microsoft/aad/msal4j/WSTrustResponse.java index 55a4984e..8057f89c 100644 --- a/src/main/java/com/microsoft/aad/msal4j/WSTrustResponse.java +++ b/src/main/java/com/microsoft/aad/msal4j/WSTrustResponse.java @@ -16,7 +16,7 @@ import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.StringWriter; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -72,7 +72,7 @@ static WSTrustResponse parse(String response, WSTrustVersion version) builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document xmlDocument = builder.parse(new ByteArrayInputStream(response - .getBytes(Charset.forName("UTF-8")))); + .getBytes(StandardCharsets.UTF_8))); XPath xPath = XPathFactory.newInstance().newXPath(); NamespaceContextImpl namespace = new NamespaceContextImpl(); xPath.setNamespaceContext(namespace); @@ -87,9 +87,8 @@ static WSTrustResponse parse(String response, WSTrustVersion version) throw new MsalServiceException( String.format("Server returned error in RSTR - ErrorCode: %s. FaultMessage: %s", responseValue.errorCode, responseValue.faultMessage.trim()), - AuthenticationErrorCode.WSTRUST_SERVICE_ERROR); - } - else { + AuthenticationErrorCode.WSTRUST_SERVICE_ERROR); + } else { parseToken(responseValue, xmlDocument, xPath, version); } @@ -97,7 +96,7 @@ static WSTrustResponse parse(String response, WSTrustVersion version) } private static void parseToken(WSTrustResponse responseValue, - Document xmlDocument, XPath xPath, WSTrustVersion version) + Document xmlDocument, XPath xPath, WSTrustVersion version) throws Exception { NodeList tokenTypeNodes = (NodeList) xPath.compile( @@ -159,7 +158,7 @@ private static void parseToken(WSTrustResponse responseValue, } private static boolean parseError(WSTrustResponse responseValue, - Document xmlDocument, XPath xPath) throws XPathExpressionException { + Document xmlDocument, XPath xPath) throws XPathExpressionException { boolean errorFound = false; NodeList faultNodes = (NodeList) xPath.compile( @@ -213,8 +212,7 @@ static String innerXml(Node node) { resultBuilder.append(sw.toString()); } - } - catch (Exception ex) { + } catch (Exception ex) { ex.printStackTrace(); } diff --git a/src/main/java/com/microsoft/aad/msal4j/XmsClientTelemetryInfo.java b/src/main/java/com/microsoft/aad/msal4j/XmsClientTelemetryInfo.java index 1a001c63..76d8ff09 100644 --- a/src/main/java/com/microsoft/aad/msal4j/XmsClientTelemetryInfo.java +++ b/src/main/java/com/microsoft/aad/msal4j/XmsClientTelemetryInfo.java @@ -19,29 +19,29 @@ class XmsClientTelemetryInfo { private String tokenAge; private String speInfo; - static XmsClientTelemetryInfo parseXmsTelemetryInfo(String headerValue){ - if(StringHelper.isBlank(headerValue)){ + static XmsClientTelemetryInfo parseXmsTelemetryInfo(String headerValue) { + if (StringHelper.isBlank(headerValue)) { return null; } String[] headerSegments = headerValue.split(","); - if(headerSegments.length == 0){ + if (headerSegments.length == 0) { return null; } String headerVersion = headerSegments[0]; XmsClientTelemetryInfo xmsClientTelemetryInfo = new XmsClientTelemetryInfo(); - if(!headerVersion.equals(EXPECTED_HEADER_VERSION)){ - return null; + if (!headerVersion.equals(EXPECTED_HEADER_VERSION)) { + return null; } Matcher matcher = matchHeaderToExpectedFormat(headerValue); - if(!matcher.matches()){ + if (!matcher.matches()) { return xmsClientTelemetryInfo; } - headerSegments = headerValue.split(",", 5 ); + headerSegments = headerValue.split(",", 5); xmsClientTelemetryInfo.serverErrorCode = headerSegments[ERROR_CODE_INDEX]; xmsClientTelemetryInfo.serverSubErrorCode = headerSegments[SUB_ERROR_CODE_INDEX]; @@ -51,7 +51,7 @@ static XmsClientTelemetryInfo parseXmsTelemetryInfo(String headerValue){ return xmsClientTelemetryInfo; } - private static Matcher matchHeaderToExpectedFormat(String header){ + private static Matcher matchHeaderToExpectedFormat(String header) { String regexp = "^[1-9]+\\.?[0-9|\\.]*,[0-9|\\.]*,[0-9|\\.]*,[^,]*[0-9\\.]*,[^,]*$"; Pattern pattern = Pattern.compile(regexp); return pattern.matcher(header); diff --git a/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java b/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java index 07ff1c9f..61ac5608 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AadInstanceDiscoveryTest.java @@ -17,7 +17,7 @@ public class AadInstanceDiscoveryTest extends PowerMockTestCase { @BeforeMethod - public void setup(){ + public void setup() { AadInstanceDiscoveryProvider.cache.clear(); } @@ -75,7 +75,7 @@ public void aadInstanceDiscoveryTest_NotSetByDeveloper() throws Exception { } @Test - public void aadInstanceDiscoveryTest_responseSetByDeveloper_validResponse() throws Exception{ + public void aadInstanceDiscoveryTest_responseSetByDeveloper_validResponse() throws Exception { String instanceDiscoveryResponse = TestHelper.readResource( this.getClass(), @@ -125,7 +125,7 @@ public void aadInstanceDiscoveryTest_responseSetByDeveloper_validResponse() thro } @Test(expectedExceptions = MsalClientException.class) - public void aadInstanceDiscoveryTest_responseSetByDeveloper_invalidJson() throws Exception{ + public void aadInstanceDiscoveryTest_responseSetByDeveloper_invalidJson() throws Exception { String instanceDiscoveryResponse = TestHelper.readResource( this.getClass(), @@ -137,7 +137,7 @@ public void aadInstanceDiscoveryTest_responseSetByDeveloper_invalidJson() throws } @Test() - public void aadInstanceDiscoveryTest_AutoDetectRegion_NoRegionDetected() throws Exception{ + public void aadInstanceDiscoveryTest_AutoDetectRegion_NoRegionDetected() throws Exception { String instanceDiscoveryResponse = TestHelper.readResource( this.getClass(), diff --git a/src/test/java/com/microsoft/aad/msal4j/AccountTest.java b/src/test/java/com/microsoft/aad/msal4j/AccountTest.java index d410e451..14a417c0 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AccountTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AccountTest.java @@ -5,8 +5,10 @@ import org.testng.Assert; import org.testng.annotations.Test; + import java.io.IOException; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Iterator; import java.util.Map; @@ -71,11 +73,11 @@ public void testMultiTenantAccount_AccessTenantProfile() throws IOException, URI } - String getEmptyBase64EncodedJson(){ + String getEmptyBase64EncodedJson() { return new String(Base64.getEncoder().encode("{}".getBytes())); } - String getJWTHeaderBase64EncodedJson(){ + String getJWTHeaderBase64EncodedJson() { return new String(Base64.getEncoder().encode("{\"alg\": \"HS256\", \"typ\": \"JWT\"}".getBytes())); } @@ -85,7 +87,7 @@ private String getTestIdToken(String environment, String tenant) throws IOExcept " \"tid\": \"" + tenant + "\"\n" + "}"; - String encodedIdToken = new String(Base64.getEncoder().encode(claims.getBytes()), "UTF-8"); + String encodedIdToken = new String(Base64.getEncoder().encode(claims.getBytes()), StandardCharsets.UTF_8); encodedIdToken = getJWTHeaderBase64EncodedJson() + POINT_DELIMITER + encodedIdToken + POINT_DELIMITER + @@ -126,7 +128,7 @@ public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) data = iTokenCacheAccessContext.tokenCache().serialize(); } - ITokenCacheAccessAspect init(String data){ + ITokenCacheAccessAspect init(String data) { this.data = data; return this; } diff --git a/src/test/java/com/microsoft/aad/msal4j/AcquireTokenSilentlyTest.java b/src/test/java/com/microsoft/aad/msal4j/AcquireTokenSilentlyTest.java index 027c6b52..db6ea553 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AcquireTokenSilentlyTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AcquireTokenSilentlyTest.java @@ -9,7 +9,7 @@ import java.util.Collections; import java.util.concurrent.CompletionException; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class AcquireTokenSilentlyTest extends PowerMockTestCase { @Test(expectedExceptions = MsalClientException.class, @@ -24,8 +24,7 @@ public void publicAppAcquireTokenSilently_emptyCache_MsalClientException() throw try { application.acquireTokenSilently(parameters).join(); - } - catch (CompletionException ex){ + } catch (CompletionException ex) { throw ex.getCause(); } } @@ -42,8 +41,7 @@ public void confidentialAppAcquireTokenSilently_emptyCache_MsalClientException() try { application.acquireTokenSilently(parameters).join(); - } - catch (CompletionException ex){ + } catch (CompletionException ex) { throw ex.getCause(); } } diff --git a/src/test/java/com/microsoft/aad/msal4j/AssertionCredentialTest.java b/src/test/java/com/microsoft/aad/msal4j/AssertionCredentialTest.java index 31535495..8f7e7450 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AssertionCredentialTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AssertionCredentialTest.java @@ -5,16 +5,16 @@ import org.testng.annotations.Test; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class AssertionCredentialTest { @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "assertion") public void testAssertionNull() { - new ClientAssertion(null); + new ClientAssertion(null); } @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "assertion") public void testAssertionEmpty() { - new ClientAssertion(""); + new ClientAssertion(""); } } diff --git a/src/test/java/com/microsoft/aad/msal4j/AuthorityTest.java b/src/test/java/com/microsoft/aad/msal4j/AuthorityTest.java index a454e653..ff0f4580 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AuthorityTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AuthorityTest.java @@ -135,21 +135,21 @@ public void testNoAuthorityPassedIn_DefaultsToCommonAuthority() { @Test public void testDoStaticInstanceDiscovery_ValidateTrue_TrustedAuthority() - throws MalformedURLException, Exception { + throws Exception { final AADAuthority aa = new AADAuthority(new URL(TestConfiguration.AAD_TENANT_ENDPOINT)); //PS Assert.assertTrue(aa.doStaticInstanceDiscovery(true)); } @Test public void testDoStaticInstanceDiscovery_ValidateTrue_UntrustedAuthority() - throws MalformedURLException, Exception { + throws Exception { final AADAuthority aa = new AADAuthority(new URL(TestConfiguration.AAD_UNKNOWN_TENANT_ENDPOINT)); //PS Assert.assertFalse(aa.doStaticInstanceDiscovery(true)); } @Test public void testDoStaticInstanceDiscovery_ValidateFalse_TrustedAuthority() - throws MalformedURLException, Exception { + throws Exception { final AADAuthority aa = new AADAuthority(new URL(TestConfiguration.AAD_UNKNOWN_TENANT_ENDPOINT)); //PS Assert.assertTrue(aa.doStaticInstanceDiscovery(false)); } diff --git a/src/test/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParametersTest.java b/src/test/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParametersTest.java index a44fc8d3..589bb339 100644 --- a/src/test/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParametersTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/AuthorizationRequestUrlParametersTest.java @@ -46,11 +46,11 @@ public void testBuilder_onlyRequiredParameters() throws UnsupportedEncodingExcep String query = authorizationUrl.getQuery(); String[] queryPairs = query.split("&"); - for(String pair: queryPairs){ + for (String pair : queryPairs) { int idx = pair.indexOf("="); queryParameters.put( URLDecoder.decode(pair.substring(0, idx), "UTF-8"), - URLDecoder.decode(pair.substring(idx+1), "UTF-8")); + URLDecoder.decode(pair.substring(idx + 1), "UTF-8")); } Assert.assertEquals(queryParameters.get("scope"), "openid profile offline_access scope"); @@ -61,7 +61,7 @@ public void testBuilder_onlyRequiredParameters() throws UnsupportedEncodingExcep } @Test(expectedExceptions = IllegalArgumentException.class) - public void testBuilder_invalidRequiredParameters(){ + public void testBuilder_invalidRequiredParameters() { String redirectUri = ""; Set scope = Collections.singleton("scope"); @@ -72,7 +72,7 @@ public void testBuilder_invalidRequiredParameters(){ } @Test - public void testBuilder_optionalParameters() throws UnsupportedEncodingException{ + public void testBuilder_optionalParameters() throws UnsupportedEncodingException { Set clientCapabilities = new HashSet<>(); clientCapabilities.add("llt"); clientCapabilities.add("ssm"); @@ -104,11 +104,11 @@ public void testBuilder_optionalParameters() throws UnsupportedEncodingException String query = authorizationUrl.getQuery(); String[] queryPairs = query.split("&"); - for(String pair: queryPairs){ + for (String pair : queryPairs) { int idx = pair.indexOf("="); queryParameters.put( URLDecoder.decode(pair.substring(0, idx), "UTF-8"), - URLDecoder.decode(pair.substring(idx+1), "UTF-8")); + URLDecoder.decode(pair.substring(idx + 1), "UTF-8")); } Assert.assertEquals(queryParameters.get("scope"), diff --git a/src/test/java/com/microsoft/aad/msal4j/CacheFormatTests.java b/src/test/java/com/microsoft/aad/msal4j/CacheFormatTests.java index f2f48471..af09cb91 100644 --- a/src/test/java/com/microsoft/aad/msal4j/CacheFormatTests.java +++ b/src/test/java/com/microsoft/aad/msal4j/CacheFormatTests.java @@ -23,6 +23,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.Time; @@ -102,7 +103,7 @@ public void compareValues(String s, Object o, Object o1, JSONCompareResult jsonC if (Math.abs(timestamp - expectations.get(o.toString())) > 1) { jsonCompareResult.fail("timestamp for " + s + " differ more than 1 sec : " + timestamp + " : " - + expectations.get(o.toString()) ); + + expectations.get(o.toString())); return; } return; @@ -150,7 +151,7 @@ public void tokenCacheEntitiesFormatTest(String folder) throws URISyntaxExceptio new TelemetryManager(null, false)); TokenRequestExecutor request = PowerMock.createPartialMock( - TokenRequestExecutor.class, new String[] { "createOauthHttpRequest" }, + TokenRequestExecutor.class, new String[]{"createOauthHttpRequest"}, new AADAuthority(new URL(AUTHORIZE_REQUEST_URL)), msalRequest, serviceBundle); OAuthHttpRequest msalOAuthHttpRequest = PowerMock.createMock(OAuthHttpRequest.class); @@ -187,7 +188,7 @@ public void tokenCacheEntitiesFormatTest(String folder) throws URISyntaxExceptio private void validateAccessTokenCacheEntity(String folder, String tokenResponse, TokenCache tokenCache) throws IOException, URISyntaxException, ParseException, JSONException { - Assert.assertEquals(tokenCache.accessTokens.size(),1 ); + Assert.assertEquals(tokenCache.accessTokens.size(), 1); String keyActual = tokenCache.accessTokens.keySet().stream().findFirst().get(); String keyExpected = readResource(folder + AT_CACHE_ENTITY_KEY); @@ -208,7 +209,7 @@ private void validateAccessTokenCacheEntity(String folder, String tokenResponse, private void validateRefreshTokenCacheEntity(String folder, TokenCache tokenCache) throws IOException, URISyntaxException, JSONException { - Assert.assertEquals(tokenCache.refreshTokens.size(),1 ); + Assert.assertEquals(tokenCache.refreshTokens.size(), 1); String actualKey = tokenCache.refreshTokens.keySet().stream().findFirst().get(); String keyExpected = readResource(folder + RT_CACHE_ENTITY_KEY); @@ -244,7 +245,7 @@ public void compareValues(String s, Object o, Object o1, JSONCompareResult jsonC private void validateIdTokenCacheEntity(String folder, TokenCache tokenCache) throws IOException, URISyntaxException, JSONException { - Assert.assertEquals(tokenCache.idTokens.size(),1 ); + Assert.assertEquals(tokenCache.idTokens.size(), 1); String actualKey = tokenCache.idTokens.keySet().stream().findFirst().get(); String keyExpected = readResource(folder + ID_TOKEN_CACHE_ENTITY_KEY); @@ -259,7 +260,7 @@ private void validateIdTokenCacheEntity(String folder, TokenCache tokenCache) private void validateAccountCacheEntity(String folder, TokenCache tokenCache) throws IOException, URISyntaxException, JSONException { - Assert.assertEquals(tokenCache.accounts.size(),1 ); + Assert.assertEquals(tokenCache.accounts.size(), 1); String actualKey = tokenCache.accounts.keySet().stream().findFirst().get(); String keyExpected = readResource(folder + ACCOUNT_CACHE_ENTITY_KEY); @@ -274,11 +275,11 @@ private void validateAccountCacheEntity(String folder, TokenCache tokenCache) private void validateAppMetadataCacheEntity(String folder, TokenCache tokenCache) throws IOException, URISyntaxException, JSONException { - if(!doesResourceExist(folder + APP_METADATA_CACHE_ENTITY)){ + if (!doesResourceExist(folder + APP_METADATA_CACHE_ENTITY)) { return; } - Assert.assertEquals(tokenCache.appMetadata.size(),1 ); + Assert.assertEquals(tokenCache.appMetadata.size(), 1); String actualKey = tokenCache.appMetadata.keySet().stream().findFirst().get(); String keyExpected = readResource(folder + APP_METADATA_ENTITY_KEY); @@ -290,11 +291,11 @@ private void validateAppMetadataCacheEntity(String folder, TokenCache tokenCache JSONAssert.assertEquals(valueExpected, actualValue, JSONCompareMode.STRICT); } - String getEmptyBase64EncodedJson(){ + String getEmptyBase64EncodedJson() { return new String(Base64.getEncoder().encode("{}".getBytes())); } - String getJWTHeaderBase64EncodedJson(){ + String getJWTHeaderBase64EncodedJson() { return new String(Base64.getEncoder().encode("{\"alg\": \"HS256\", \"typ\": \"JWT\"}".getBytes())); } @@ -307,7 +308,7 @@ private String getTokenResponse(String folder) throws IOException, URISyntaxExce private String getIdToken(String folder) throws IOException, URISyntaxException { String tokenResponseIdToken = readResource(folder + TOKEN_RESPONSE_ID_TOKEN); - String encodedIdToken = new String(Base64.getEncoder().encode(tokenResponseIdToken.getBytes()), "UTF-8"); + String encodedIdToken = new String(Base64.getEncoder().encode(tokenResponseIdToken.getBytes()), StandardCharsets.UTF_8); encodedIdToken = getJWTHeaderBase64EncodedJson() + POINT_DELIMITER + encodedIdToken + POINT_DELIMITER + diff --git a/src/test/java/com/microsoft/aad/msal4j/ClientCertificateTest.java b/src/test/java/com/microsoft/aad/msal4j/ClientCertificateTest.java index b74461f6..c54aef87 100644 --- a/src/test/java/com/microsoft/aad/msal4j/ClientCertificateTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/ClientCertificateTest.java @@ -14,8 +14,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.testng.annotations.Test; -@Test(groups = { "checkin" }) -@PrepareForTest({ RSAPrivateKey.class }) +@Test(groups = {"checkin"}) +@PrepareForTest({RSAPrivateKey.class}) public class ClientCertificateTest extends AbstractMsalTests { @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "PrivateKey is null or empty") diff --git a/src/test/java/com/microsoft/aad/msal4j/DeviceCodeFlowTest.java b/src/test/java/com/microsoft/aad/msal4j/DeviceCodeFlowTest.java index 96914816..91cebf30 100644 --- a/src/test/java/com/microsoft/aad/msal4j/DeviceCodeFlowTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/DeviceCodeFlowTest.java @@ -27,8 +27,8 @@ import static com.microsoft.aad.msal4j.TestConfiguration.*; -@Test(groups = { "checkin" }) -@PrepareForTest({HttpHelper.class, PublicClientApplication.class }) +@Test(groups = {"checkin"}) +@PrepareForTest({HttpHelper.class, PublicClientApplication.class}) public class DeviceCodeFlowTest extends PowerMockTestCase { private PublicClientApplication app = null; @@ -37,11 +37,9 @@ public IObjectFactory getObjectFactory() { return new org.powermock.modules.testng.PowerMockObjectFactory(); } - public static Map getQueryMap(String query) - { + public static Map getQueryMap(String query) { Map map = new HashMap<>(); - for (String param : query.split("&")) - { + for (String param : query.split("&")) { map.put(param.split("=")[0], param.split("=")[1]); } return map; @@ -60,7 +58,7 @@ public static Map getQueryMap(String query) @Test public void deviceCodeFlowTest() throws Exception { app = PowerMock.createPartialMock(PublicClientApplication.class, - new String[] { "acquireTokenCommon" }, + new String[]{"acquireTokenCommon"}, PublicClientApplication.builder(TestConfiguration.AAD_CLIENT_ID) .authority(TestConfiguration.AAD_TENANT_ENDPOINT)); @@ -104,7 +102,7 @@ public void deviceCodeFlowTest() throws Exception { AtomicReference deviceCodeCorrelationId = new AtomicReference<>(); - Consumer deviceCodeConsumer = (DeviceCode deviceCode) ->{ + Consumer deviceCodeConsumer = (DeviceCode deviceCode) -> { // validate returned Device Code object Assert.assertNotNull(deviceCode); @@ -159,7 +157,8 @@ public void executeAcquireDeviceCode_B2CAuthorityUsed_IllegalArgumentExceptionTh app.acquireToken (DeviceCodeFlowParameters - .builder(Collections.singleton(AAD_RESOURCE_ID), (DeviceCode deviceCode) -> {}) + .builder(Collections.singleton(AAD_RESOURCE_ID), (DeviceCode deviceCode) -> { + }) .build()); } @@ -167,12 +166,13 @@ public void executeAcquireDeviceCode_B2CAuthorityUsed_IllegalArgumentExceptionTh public void executeAcquireDeviceCode_AuthenticaionPendingErrorReturned_AuthenticationExceptionThrown() throws Exception { - TelemetryManager telemetryManager = new TelemetryManager(null, false); + TelemetryManager telemetryManager = new TelemetryManager(null, false); AtomicReference> futureReference = new AtomicReference<>(); - Consumer deviceCodeConsumer = (DeviceCode deviceCode) -> { }; + Consumer deviceCodeConsumer = (DeviceCode deviceCode) -> { + }; app = PublicClientApplication.builder("client_id") .authority(AAD_TENANT_ENDPOINT) @@ -184,7 +184,7 @@ public void executeAcquireDeviceCode_AuthenticaionPendingErrorReturned_Authentic DeviceCodeFlowParameters.builder(Collections.singleton("default-scope"), deviceCodeConsumer) .build(); - final DeviceCodeFlowRequest dcr = new DeviceCodeFlowRequest( + final DeviceCodeFlowRequest dcr = new DeviceCodeFlowRequest( parameters, futureReference, app, diff --git a/src/test/java/com/microsoft/aad/msal4j/HttpUtilsTest.java b/src/test/java/com/microsoft/aad/msal4j/HttpUtilsTest.java index 012a9379..46b3da59 100644 --- a/src/test/java/com/microsoft/aad/msal4j/HttpUtilsTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/HttpUtilsTest.java @@ -12,7 +12,7 @@ import java.util.List; import java.util.Map; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class HttpUtilsTest { private final String COOKIE_HEADER_NAME = "Set-Cookie"; @@ -20,9 +20,9 @@ public class HttpUtilsTest { private final String COOKIE_HEADER_VALUE_2 = "u32t4o3tb3gg43"; @Test - public void testHttpUtils_singleValueHeader(){ + public void testHttpUtils_singleValueHeader() { - Map> singleValuedHeader = new HashMap>(){{ + Map> singleValuedHeader = new HashMap>() {{ put(COOKIE_HEADER_NAME, Collections.singletonList(COOKIE_HEADER_VALUE_1)); }}; @@ -31,9 +31,9 @@ public void testHttpUtils_singleValueHeader(){ } @Test - public void testHttpUtils_multiValueHeader(){ + public void testHttpUtils_multiValueHeader() { - Map> multiValuedHeader = new HashMap>(){{ + Map> multiValuedHeader = new HashMap>() {{ put(COOKIE_HEADER_NAME, Arrays.asList(COOKIE_HEADER_VALUE_1, COOKIE_HEADER_VALUE_2)); }}; @@ -43,9 +43,9 @@ public void testHttpUtils_multiValueHeader(){ } @Test - public void testHttpUtils_HeaderValueNull(){ + public void testHttpUtils_HeaderValueNull() { - Map> nullValuedHeader = new HashMap>(){{ + Map> nullValuedHeader = new HashMap>() {{ put(COOKIE_HEADER_NAME, null); }}; diff --git a/src/test/java/com/microsoft/aad/msal4j/MexParserTest.java b/src/test/java/com/microsoft/aad/msal4j/MexParserTest.java index b8f7872d..948d6a36 100644 --- a/src/test/java/com/microsoft/aad/msal4j/MexParserTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/MexParserTest.java @@ -11,19 +11,19 @@ import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class MexParserTest { @BeforeTest - public void setup(){ + public void setup() { System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"); } - + @AfterTest - public void cleanup(){ + public void cleanup() { System.clearProperty("javax.xml.parsers.DocumentBuilderFactory"); } - + @Test public void testMexParsing() throws Exception { @@ -44,14 +44,14 @@ public void testMexParsing() throws Exception { Assert.assertEquals(endpoint.getUrl(), "https://msft.sts.microsoft.com/adfs/services/trust/13/usernamemixed"); } - + @Test public void testMexParsingWs2005() throws Exception { StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader( this.getClass().getResource( - TestConfiguration.AAD_MEX_2005_RESPONSE_FILE).getFile()))) { + TestConfiguration.AAD_MEX_2005_RESPONSE_FILE).getFile()))) { String line = br.readLine(); while (line != null) { @@ -62,7 +62,7 @@ public void testMexParsingWs2005() throws Exception { } BindingPolicy endpoint = MexParser.getWsTrustEndpointFromMexResponse(sb .toString(), false); - Assert.assertEquals(endpoint.getUrl(),"https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed"); + Assert.assertEquals(endpoint.getUrl(), "https://msft.sts.microsoft.com/adfs/services/trust/2005/usernamemixed"); } @Test diff --git a/src/test/java/com/microsoft/aad/msal4j/MsalOauthAuthorizatonGrantTest.java b/src/test/java/com/microsoft/aad/msal4j/MsalOauthAuthorizatonGrantTest.java index 9df15577..dd8433a9 100644 --- a/src/test/java/com/microsoft/aad/msal4j/MsalOauthAuthorizatonGrantTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/MsalOauthAuthorizatonGrantTest.java @@ -31,7 +31,7 @@ public void testToParameters() throws URISyntaxException { final OAuthAuthorizationGrant grant = new OAuthAuthorizationGrant( new AuthorizationCodeGrant(new AuthorizationCode("grant"), new URI("http://microsoft.com")), - (Map>) null); + null); Assert.assertNotNull(grant); Assert.assertNotNull(grant.toParameters()); } diff --git a/src/test/java/com/microsoft/aad/msal4j/OAuthRequestValidationTest.java b/src/test/java/com/microsoft/aad/msal4j/OAuthRequestValidationTest.java index 262e16f3..9e3bf1ed 100644 --- a/src/test/java/com/microsoft/aad/msal4j/OAuthRequestValidationTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/OAuthRequestValidationTest.java @@ -62,7 +62,7 @@ public class OAuthRequestValidationTest extends AbstractMsalTests { @SuppressWarnings("unchecked") @BeforeMethod - public void init() throws Exception{ + public void init() throws Exception { PowerMock.mockStatic(HttpHelper.class); HttpResponse httpResponse = new HttpResponse(); diff --git a/src/test/java/com/microsoft/aad/msal4j/OauthHttpRequestTest.java b/src/test/java/com/microsoft/aad/msal4j/OauthHttpRequestTest.java index 1c3bfd1d..8ef4f776 100644 --- a/src/test/java/com/microsoft/aad/msal4j/OauthHttpRequestTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/OauthHttpRequestTest.java @@ -22,8 +22,8 @@ import static org.testng.Assert.assertNotNull; -@Test(groups = { "checkin" }) -@PrepareForTest({ OAuthHttpRequest.class }) +@Test(groups = {"checkin"}) +@PrepareForTest({OAuthHttpRequest.class}) public class OauthHttpRequestTest extends AbstractMsalTests { @Test diff --git a/src/test/java/com/microsoft/aad/msal4j/PublicClientApplicationTest.java b/src/test/java/com/microsoft/aad/msal4j/PublicClientApplicationTest.java index 4e44e1fe..16adab0e 100644 --- a/src/test/java/com/microsoft/aad/msal4j/PublicClientApplicationTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/PublicClientApplicationTest.java @@ -17,8 +17,8 @@ import java.util.concurrent.Future; @PowerMockIgnore({"javax.net.ssl.*"}) -@Test(groups = { "checkin" }) -@PrepareForTest({ PublicClientApplication.class, +@Test(groups = {"checkin"}) +@PrepareForTest({PublicClientApplication.class, ClientCertificate.class, UserDiscoveryRequest.class}) public class PublicClientApplicationTest extends PowerMockTestCase { @@ -28,7 +28,7 @@ public class PublicClientApplicationTest extends PowerMockTestCase { @Test public void testAcquireToken_Username_Password() throws Exception { app = PowerMock.createPartialMock(PublicClientApplication.class, - new String[] { "acquireTokenCommon" }, + new String[]{"acquireTokenCommon"}, PublicClientApplication.builder(TestConfiguration.AAD_CLIENT_ID) .authority(TestConfiguration.AAD_TENANT_ENDPOINT)); diff --git a/src/test/java/com/microsoft/aad/msal4j/RequestThrottlingTest.java b/src/test/java/com/microsoft/aad/msal4j/RequestThrottlingTest.java index 2344d1e1..cd04b926 100644 --- a/src/test/java/com/microsoft/aad/msal4j/RequestThrottlingTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/RequestThrottlingTest.java @@ -21,7 +21,7 @@ public class RequestThrottlingTest extends AbstractMsalTests { public final Integer THROTTLE_IN_SEC = 1; @BeforeMethod - void init(){ + void init() { ThrottlingCache.DEFAULT_THROTTLING_TIME_SEC = THROTTLE_IN_SEC; } @@ -102,11 +102,10 @@ private PublicClientApplication getClientApplicationMockedWithOneTokenEndpointRe headers.put("Content-Type", Arrays.asList("application/json")); httpResponse.addHeaders(headers); - if(responseType == TokenEndpointResponseType.STATUS_CODE_500){ + if (responseType == TokenEndpointResponseType.STATUS_CODE_500) { // expected to called two times due to retry logic EasyMock.expect(httpClientMock.send(anyObject())).andReturn(httpResponse).times(2); - } - else{ + } else { EasyMock.expect(httpClientMock.send(anyObject())).andReturn(httpResponse).times(1); } @@ -187,12 +186,12 @@ public void STSResponseContains_StatusCode429_RetryAfterHeader() throws Exceptio } @Test - public void STSResponseContains_StatusCode500() throws Exception { + public void STSResponseContains_StatusCode500() throws Exception { throttlingTest(TokenEndpointResponseType.STATUS_CODE_500); } @Test - public void STSResponseContains_StatusCode500_RetryAfterHeader() throws Exception { + public void STSResponseContains_StatusCode500_RetryAfterHeader() throws Exception { // using big value for DEFAULT_THROTTLING_TIME_SEC to make sure that RetryAfterHeader value used instead ThrottlingCache.DEFAULT_THROTTLING_TIME_SEC = 1000; throttlingTest(TokenEndpointResponseType.STATUS_CODE_500_RETRY_AFTER_HEADER); diff --git a/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java b/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java index 1945dba0..6d826cf5 100644 --- a/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java +++ b/src/test/java/com/microsoft/aad/msal4j/ServerTelemetryTests.java @@ -26,7 +26,7 @@ public class ServerTelemetryTests { private final static String ERROR = "invalid_grant"; @Test - public void serverTelemetryHeaders_correctSchema(){ + public void serverTelemetryHeaders_correctSchema() { CurrentRequest currentRequest = new CurrentRequest(PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE); @@ -67,10 +67,10 @@ public void serverTelemetryHeaders_correctSchema(){ } @Test - public void serverTelemetryHeaders_previewsRequestNull(){ + public void serverTelemetryHeaders_previewsRequestNull() { ServerSideTelemetry serverSideTelemetry = new ServerSideTelemetry(); - for(int i = 0; i < 3; i++){ + for (int i = 0; i < 3; i++) { serverSideTelemetry.incrementSilentSuccessfulCount(); } @@ -80,47 +80,47 @@ public void serverTelemetryHeaders_previewsRequestNull(){ } @Test - public void serverTelemetryHeader_testMaximumHeaderSize(){ + public void serverTelemetryHeader_testMaximumHeaderSize() { ServerSideTelemetry serverSideTelemetry = new ServerSideTelemetry(); - for(int i = 0; i <20; i++){ + for (int i = 0; i < 20; i++) { String correlationId = UUID.randomUUID().toString(); serverSideTelemetry.addFailedRequestTelemetry(PUBLIC_API_ID, correlationId, ERROR); } - Map headers = serverSideTelemetry.getServerTelemetryHeaderMap(); + Map headers = serverSideTelemetry.getServerTelemetryHeaderMap(); - String lastRequest = headers.get(LAST_REQUEST_HEADER_NAME); + String lastRequest = headers.get(LAST_REQUEST_HEADER_NAME); - byte[] lastRequestBytes = lastRequest.getBytes(StandardCharsets.UTF_8); + byte[] lastRequestBytes = lastRequest.getBytes(StandardCharsets.UTF_8); - Assert.assertTrue(lastRequestBytes.length <= 350); + Assert.assertTrue(lastRequestBytes.length <= 350); } @Test - public void serverTelemetryHeaders_multipleThreadsWrite(){ + public void serverTelemetryHeaders_multipleThreadsWrite() { ServerSideTelemetry serverSideTelemetry = new ServerSideTelemetry(); ExecutorService executor = Executors.newFixedThreadPool(10); - try{ - for (int i=0; i < 10; i++){ + try { + for (int i = 0; i < 10; i++) { executor.execute(new FailedRequestRunnable(serverSideTelemetry)); executor.execute(new SilentSuccessfulRequestRunnable(serverSideTelemetry)); } - } catch (Exception ex){ + } catch (Exception ex) { ex.printStackTrace(); } executor.shutdown(); - try{ - Thread.sleep( 1000); - } catch(InterruptedException ex){ + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { ex.printStackTrace(); } - Map headers = serverSideTelemetry.getServerTelemetryHeaderMap(); + Map headers = serverSideTelemetry.getServerTelemetryHeaderMap(); List previousRequestHeader = Arrays.asList(headers.get(LAST_REQUEST_HEADER_NAME).split("\\|")); @@ -132,10 +132,10 @@ public void serverTelemetryHeaders_multipleThreadsWrite(){ List fourthSegment = Arrays.asList(previousRequestHeader.get(3).split(",")); Assert.assertEquals(fourthSegment.size(), 6); - Assert.assertTrue(headers.get(LAST_REQUEST_HEADER_NAME).getBytes(StandardCharsets.UTF_8).length < 350); + Assert.assertTrue(headers.get(LAST_REQUEST_HEADER_NAME).getBytes(StandardCharsets.UTF_8).length < 350); // Not all requests fit into first header, so they would get dispatched in the next request - Map secondRequest = serverSideTelemetry.getServerTelemetryHeaderMap(); + Map secondRequest = serverSideTelemetry.getServerTelemetryHeaderMap(); previousRequestHeader = Arrays.asList(secondRequest.get(LAST_REQUEST_HEADER_NAME).split("\\|")); @@ -147,12 +147,12 @@ public void serverTelemetryHeaders_multipleThreadsWrite(){ fourthSegment = Arrays.asList(previousRequestHeader.get(3).split(",")); Assert.assertEquals(fourthSegment.size(), 4); - Assert.assertTrue(secondRequest.get(LAST_REQUEST_HEADER_NAME).getBytes(StandardCharsets.UTF_8).length < 350); + Assert.assertTrue(secondRequest.get(LAST_REQUEST_HEADER_NAME).getBytes(StandardCharsets.UTF_8).length < 350); } @Test - public void serverTelemetryHeaders_testRegionTelemetry() throws Exception{ + public void serverTelemetryHeaders_testRegionTelemetry() throws Exception { CurrentRequest currentRequest = new CurrentRequest(PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE); ServerSideTelemetry serverSideTelemetry = new ServerSideTelemetry(); @@ -203,18 +203,18 @@ class FailedRequestRunnable implements Runnable { ServerSideTelemetry telemetry; - FailedRequestRunnable(ServerSideTelemetry telemetry){ + FailedRequestRunnable(ServerSideTelemetry telemetry) { this.telemetry = telemetry; } @Override - public void run(){ + public void run() { Random rand = new Random(); int n = rand.nextInt(250); try { Thread.sleep(n); - } catch (InterruptedException ex){ + } catch (InterruptedException ex) { ex.printStackTrace(); } String correlationId = UUID.randomUUID().toString(); @@ -226,12 +226,12 @@ class SilentSuccessfulRequestRunnable implements Runnable { ServerSideTelemetry telemetry; - SilentSuccessfulRequestRunnable(ServerSideTelemetry telemetry){ + SilentSuccessfulRequestRunnable(ServerSideTelemetry telemetry) { this.telemetry = telemetry; } @Override - public void run(){ + public void run() { telemetry.incrementSilentSuccessfulCount(); } } diff --git a/src/test/java/com/microsoft/aad/msal4j/TelemetryTests.java b/src/test/java/com/microsoft/aad/msal4j/TelemetryTests.java index ed49f0c4..7f159d36 100644 --- a/src/test/java/com/microsoft/aad/msal4j/TelemetryTests.java +++ b/src/test/java/com/microsoft/aad/msal4j/TelemetryTests.java @@ -14,10 +14,10 @@ import java.util.List; import java.util.function.Consumer; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class TelemetryTests { - private List> eventsReceived = new ArrayList<>(); + private List> eventsReceived = new ArrayList<>(); private String tenantId = "tenantId123"; private String clientId = "a1b3c3d4"; @@ -28,19 +28,19 @@ private class MyTelemetryConsumer { 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)); + System.out.print("Event Name: " + event.get("event_name")); + event.entrySet().forEach(entry -> System.out.println(" " + entry)); }); }; } @AfterMethod - private void cleanUp(){ + private void cleanUp() { eventsReceived.clear(); } @Test - public void telemetryConsumerRegistration_ConsumerNotNullTest(){ + public void telemetryConsumerRegistration_ConsumerNotNullTest() { PublicClientApplication app = PublicClientApplication.builder("a1b2c3") .telemetryConsumer(new MyTelemetryConsumer().telemetryConsumer) .build(); @@ -49,7 +49,7 @@ public void telemetryConsumerRegistration_ConsumerNotNullTest(){ } @Test - public void telemetryManagerFlush_EventCountTest(){ + public void telemetryManagerFlush_EventCountTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -65,14 +65,14 @@ public void telemetryManagerFlush_EventCountTest(){ httpEvent1.setHttpResponseStatus(200); telemetryManager.stopEvent(reqId, httpEvent1); - telemetryManager.flush(reqId,clientId ); + telemetryManager.flush(reqId, clientId); // 1 Default event, 1 API event, 1 Http event Assert.assertEquals(eventsReceived.size(), 3); } @Test - public void onSendFailureTrue_SkipEventsIfSuccessfulTest(){ + public void onSendFailureTrue_SkipEventsIfSuccessfulTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; // Only send on failure @@ -90,7 +90,7 @@ public void onSendFailureTrue_SkipEventsIfSuccessfulTest(){ httpEvent1.setHttpResponseStatus(200); telemetryManager.stopEvent(reqId, httpEvent1); - telemetryManager.flush(reqId,clientId ); + telemetryManager.flush(reqId, clientId); // API event was successful, so count should be 0 Assert.assertEquals(eventsReceived.size(), 0); @@ -107,18 +107,18 @@ public void onSendFailureTrue_SkipEventsIfSuccessfulTest(){ httpEvent2.setHttpResponseStatus(200); telemetryManager.stopEvent(reqId2, httpEvent2); - telemetryManager.flush(reqId2,clientId ); + telemetryManager.flush(reqId2, clientId); // API event failed, so count should be 3 (1 default, 1 Api, 1 http) Assert.assertEquals(eventsReceived.size(), 3); } @Test - public void telemetryInternalApi_ScrubTenantFromUriTest() throws Exception{ - Assert.assertEquals(Event.scrubTenant(new URI("https://login.microsoftonline.com/common/oauth2/v2.0/token")) , + public void telemetryInternalApi_ScrubTenantFromUriTest() throws Exception { + Assert.assertEquals(Event.scrubTenant(new URI("https://login.microsoftonline.com/common/oauth2/v2.0/token")), "https://login.microsoftonline.com//oauth2/v2.0/token"); - Assert.assertEquals( Event.scrubTenant(new URI("https://login.microsoftonline.com/common")), + Assert.assertEquals(Event.scrubTenant(new URI("https://login.microsoftonline.com/common")), "https://login.microsoftonline.com/"); Assert.assertEquals(Event.scrubTenant(new URI("https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_ROPC_Auth")), @@ -130,7 +130,7 @@ public void telemetryInternalApi_ScrubTenantFromUriTest() throws Exception{ } @Test - public void telemetryContainsDefaultEventTest(){ + public void telemetryContainsDefaultEventTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; // Only send on failure @@ -147,13 +147,13 @@ public void telemetryContainsDefaultEventTest(){ httpEvent1.setHttpResponseStatus(200); telemetryManager.stopEvent(reqId, httpEvent1); - telemetryManager.flush(reqId,clientId ); + telemetryManager.flush(reqId, clientId); Assert.assertEquals(eventsReceived.get(0).get("event_name"), "msal.default_event"); } @Test - public void telemetryFlushEventWithoutStopping_OrphanedEventIncludedTest(){ + public void telemetryFlushEventWithoutStopping_OrphanedEventIncludedTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -169,14 +169,14 @@ public void telemetryFlushEventWithoutStopping_OrphanedEventIncludedTest(){ // didn't stop http event, should still be sent telemetryManager.stopEvent(reqId, apiEvent1); - telemetryManager.flush(reqId,clientId ); + telemetryManager.flush(reqId, clientId); Assert.assertEquals(eventsReceived.size(), 3); Assert.assertTrue(eventsReceived.stream().anyMatch(event -> event.get("event_name").equals("msal.http_event"))); } @Test - public void telemetryStopEventWithoutStarting_NoExceptionThrownTest(){ + public void telemetryStopEventWithoutStarting_NoExceptionThrownTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -201,7 +201,7 @@ public void telemetryStopEventWithoutStarting_NoExceptionThrownTest(){ } @Test - public void piiLoggingEnabled_ApiEventHashTest(){ + public void piiLoggingEnabled_ApiEventHashTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -220,7 +220,7 @@ public void piiLoggingEnabled_ApiEventHashTest(){ } @Test - public void piiLoggingEnabledFalse_TenantIdUserIdSetToNullTest(){ + public void piiLoggingEnabledFalse_TenantIdUserIdSetToNullTest() { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -238,7 +238,7 @@ public void piiLoggingEnabledFalse_TenantIdUserIdSetToNullTest(){ } @Test - public void authorityNotInTrustedHostList_AuthorityIsNullTest() throws URISyntaxException{ + public void authorityNotInTrustedHostList_AuthorityIsNullTest() throws URISyntaxException { Consumer>> telemetryConsumer = new MyTelemetryConsumer().telemetryConsumer; TelemetryManager telemetryManager = new TelemetryManager(telemetryConsumer, false); @@ -263,8 +263,8 @@ public void authorityNotInTrustedHostList_AuthorityIsNullTest() throws URISyntax } @Test - public void xmsCliTelemetryTest_CorrectFormatTest(){ - String responseHeader = "1,0,0,," ; + public void xmsCliTelemetryTest_CorrectFormatTest() { + String responseHeader = "1,0,0,,"; XmsClientTelemetryInfo info = XmsClientTelemetryInfo.parseXmsTelemetryInfo(responseHeader); Assert.assertEquals(info.getServerErrorCode(), "0"); @@ -274,8 +274,8 @@ public void xmsCliTelemetryTest_CorrectFormatTest(){ } @Test - public void xmsCliTelemetryTest_IncorrectFormatTest(){ - String responseHeader = "1,2,3,4,5,6"; + public void xmsCliTelemetryTest_IncorrectFormatTest() { + String responseHeader = "1,2,3,4,5,6"; XmsClientTelemetryInfo info = XmsClientTelemetryInfo.parseXmsTelemetryInfo(responseHeader); Assert.assertNull(info.getServerErrorCode()); @@ -285,34 +285,34 @@ public void xmsCliTelemetryTest_IncorrectFormatTest(){ } @Test - public void xmsCliTelemetryTest_IncorrectHeaderTest(){ + public void xmsCliTelemetryTest_IncorrectHeaderTest() { String responseHeader = "3,0,0,,"; XmsClientTelemetryInfo info = XmsClientTelemetryInfo.parseXmsTelemetryInfo(responseHeader); Assert.assertNull(info); } - private ApiEvent createApiEvent(Boolean logPii){ + private ApiEvent createApiEvent(Boolean logPii) { ApiEvent apiEvent1; try { apiEvent1 = new ApiEvent(logPii); apiEvent1.setAuthority(new URI("https://login.microsoft.com")); apiEvent1.setTenantId(tenantId); - } catch(URISyntaxException e){ + } catch (URISyntaxException e) { throw new RuntimeException(e.getMessage()); } return apiEvent1; } - private HttpEvent createHttpEvent(){ + private HttpEvent createHttpEvent() { HttpEvent httpEvent1; try { httpEvent1 = new HttpEvent(); httpEvent1.setHttpPath(new URI("https://contoso.com")); httpEvent1.setHttpMethod("GET"); httpEvent1.setQueryParameters("?a=1&b=2"); - } catch(URISyntaxException e){ + } catch (URISyntaxException e) { throw new RuntimeException(e.getMessage()); } return httpEvent1; diff --git a/src/test/java/com/microsoft/aad/msal4j/TestConfiguration.java b/src/test/java/com/microsoft/aad/msal4j/TestConfiguration.java index b27cb58c..15aa72db 100644 --- a/src/test/java/com/microsoft/aad/msal4j/TestConfiguration.java +++ b/src/test/java/com/microsoft/aad/msal4j/TestConfiguration.java @@ -28,10 +28,10 @@ public final class TestConfiguration { public final static String B2C_HOST_NAME = "msidlabb2c.b2clogin.com"; public final static String B2C_SIGN_IN_POLICY = "B2C_1_SignInPolicy"; - public final static String B2C_AUTHORITY = "https://" + B2C_HOST_NAME + + public final static String B2C_AUTHORITY = "https://" + B2C_HOST_NAME + "/tfp/msidlabb2c.onmicrosoft.com/" + B2C_SIGN_IN_POLICY; - public final static String B2C_AUTHORITY_ENDPOINT = "https://" + B2C_HOST_NAME + + public final static String B2C_AUTHORITY_ENDPOINT = "https://" + B2C_HOST_NAME + "/msidlabb2c.onmicrosoft.com"; public final static String B2C_AUTHORITY_CUSTOM_PORT = "https://login.microsoftonline.in:444/tfp/tenant/policy"; public final static String B2C_AUTHORITY_CUSTOM_PORT_TAIL_SLASH = "https://login.microsoftonline.in:444/tfp/tenant/policy/"; diff --git a/src/test/java/com/microsoft/aad/msal4j/TokenRequestExecutorTest.java b/src/test/java/com/microsoft/aad/msal4j/TokenRequestExecutorTest.java index aec766bc..efe3ac80 100644 --- a/src/test/java/com/microsoft/aad/msal4j/TokenRequestExecutorTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/TokenRequestExecutorTest.java @@ -22,7 +22,7 @@ import java.util.Collections; import java.util.HashMap; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) @PrepareForTest(TokenErrorResponse.class) public class TokenRequestExecutorTest extends AbstractMsalTests { @@ -139,7 +139,7 @@ public void testConstructor() throws MalformedURLException, .scopes(Collections.singleton("default-scope")) .build(); - final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( + final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( parameters, app, new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters)); @@ -162,7 +162,7 @@ public void testToOAuthRequestNonEmptyCorrelationId() .scopes(Collections.singleton("default-scope")) .build(); - AuthorizationCodeRequest acr = new AuthorizationCodeRequest( + AuthorizationCodeRequest acr = new AuthorizationCodeRequest( parameters, app, new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters)); @@ -191,7 +191,7 @@ public void testToOAuthRequestNullCorrelationId_NullClientAuth() .scopes(Collections.singleton("default-scope")) .build(); - final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( + final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( parameters, app, new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters)); @@ -216,7 +216,7 @@ public void testExecuteOAuth_Success() throws SerializeException, ParseException .scopes(Collections.singleton("default-scope")) .build(); - final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( + final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( parameters, app, new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters)); @@ -227,7 +227,7 @@ public void testExecuteOAuth_Success() throws SerializeException, ParseException new TelemetryManager(null, false)); final TokenRequestExecutor request = PowerMock.createPartialMock( - TokenRequestExecutor.class, new String[] { "createOauthHttpRequest" }, + TokenRequestExecutor.class, new String[]{"createOauthHttpRequest"}, new AADAuthority(new URL(TestConstants.ORGANIZATIONS_AUTHORITY)), acr, serviceBundle); final OAuthHttpRequest msalOAuthHttpRequest = PowerMock @@ -274,7 +274,7 @@ public void testExecuteOAuth_Failure() throws SerializeException, .scopes(Collections.singleton("default-scope")) .build(); - final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( + final AuthorizationCodeRequest acr = new AuthorizationCodeRequest( parameters, app, new RequestContext(app, PublicApi.ACQUIRE_TOKEN_BY_AUTHORIZATION_CODE, parameters)); @@ -285,7 +285,7 @@ public void testExecuteOAuth_Failure() throws SerializeException, new TelemetryManager(null, false)); final TokenRequestExecutor request = PowerMock.createPartialMock( - TokenRequestExecutor.class, new String[] { "createOauthHttpRequest" }, + TokenRequestExecutor.class, new String[]{"createOauthHttpRequest"}, new AADAuthority(new URL(TestConstants.ORGANIZATIONS_AUTHORITY)), acr, serviceBundle); final OAuthHttpRequest msalOAuthHttpRequest = PowerMock .createMock(OAuthHttpRequest.class); @@ -316,8 +316,7 @@ public void testExecuteOAuth_Failure() throws SerializeException, try { request.executeTokenRequest(); PowerMock.verifyAll(); - } - finally { + } finally { PowerMock.reset(request, msalOAuthHttpRequest, httpResponse, TokenErrorResponse.class, errorResponse); } diff --git a/src/test/java/com/microsoft/aad/msal4j/TokenResponseTest.java b/src/test/java/com/microsoft/aad/msal4j/TokenResponseTest.java index 2e4d685b..2eaa76f8 100644 --- a/src/test/java/com/microsoft/aad/msal4j/TokenResponseTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/TokenResponseTest.java @@ -4,6 +4,7 @@ package com.microsoft.aad.msal4j; import java.text.ParseException; + import com.nimbusds.jwt.JWT; import com.nimbusds.oauth2.sdk.token.AccessToken; import com.nimbusds.oauth2.sdk.token.BearerAccessToken; @@ -13,7 +14,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class TokenResponseTest extends AbstractMsalTests { private final String idToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1THdqcHdBSk9NOW4tQSJ9." @@ -37,7 +38,7 @@ public class TokenResponseTest extends AbstractMsalTests { public void testConstructor() throws ParseException { final TokenResponse response = new TokenResponse( new BearerAccessToken("access_token"), new RefreshToken( - "refresh_token"), idToken, null, null, expiresIn, extExpiresIn, null, refreshIn); + "refresh_token"), idToken, null, null, expiresIn, extExpiresIn, null, refreshIn); Assert.assertNotNull(response); OIDCTokens tokens = response.getOIDCTokens(); Assert.assertNotNull(tokens); diff --git a/src/test/java/com/microsoft/aad/msal4j/WSTrustRequestTest.java b/src/test/java/com/microsoft/aad/msal4j/WSTrustRequestTest.java index cca651b9..151b7804 100644 --- a/src/test/java/com/microsoft/aad/msal4j/WSTrustRequestTest.java +++ b/src/test/java/com/microsoft/aad/msal4j/WSTrustRequestTest.java @@ -7,7 +7,7 @@ import org.testng.Assert; import org.testng.annotations.Test; -@Test(groups = { "checkin" }) +@Test(groups = {"checkin"}) public class WSTrustRequestTest { @Test @@ -33,7 +33,7 @@ public void buildMessage_cloudAudienceUrnEmpty() throws Exception { Assert.assertTrue(msg.contains("" + WSTrustRequest.DEFAULT_APPLIES_TO + "")); } - + @Test public void buildMessage_integrated() throws Exception { String msg = WSTrustRequest.buildMessage("address", null, @@ -43,7 +43,8 @@ public void buildMessage_integrated() throws Exception { Assert.assertTrue(!msg.contains("