-
Notifications
You must be signed in to change notification settings - Fork 148
Pass optional tenant override to internal silent call #886
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0dcdc8b
Fix tenant override API not being properly used in certain confidenti…
Avery-Dunn f042744
Replace integration test with unit test
Avery-Dunn 0874c4c
Improve unit test
Avery-Dunn 51d1fff
Merge branch 'dev' of https://github.com/AzureAD/microsoft-authentica…
Avery-Dunn 82633f2
PR feedback, refactor common code
Avery-Dunn a1a394a
Add unit test for client credential flow
Avery-Dunn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
87 changes: 87 additions & 0 deletions
87
msal4j-sdk/src/test/java/com/microsoft/aad/msal4j/OnBehalfOfTests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.microsoft.aad.msal4j; | ||
|
||
import java.util.Collections; | ||
import java.util.HashMap; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.junit.jupiter.api.extension.ExtendWith; | ||
import org.mockito.junit.jupiter.MockitoExtension; | ||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
import static org.junit.jupiter.api.Assertions.assertNotEquals; | ||
import static org.mockito.ArgumentMatchers.any; | ||
import static org.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.times; | ||
import static org.mockito.Mockito.verify; | ||
import static org.mockito.Mockito.when; | ||
|
||
@ExtendWith(MockitoExtension.class) | ||
class OnBehalfOfTests { | ||
|
||
@Test | ||
void OnBehalfOf_InternalCacheLookup_Success() throws Exception { | ||
DefaultHttpClient httpClientMock = mock(DefaultHttpClient.class); | ||
|
||
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(new HashMap<>()))); | ||
|
||
ConfidentialClientApplication cca = | ||
ConfidentialClientApplication.builder("clientId", ClientCredentialFactory.createFromSecret("password")) | ||
bgavrilMS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.authority("https://login.microsoftonline.com/tenant/") | ||
.instanceDiscovery(false) | ||
.validateAuthority(false) | ||
.httpClient(httpClientMock) | ||
.build(); | ||
|
||
OnBehalfOfParameters parameters = OnBehalfOfParameters.builder(Collections.singleton("scopes"), new UserAssertion(TestHelper.signedAssertion)).build(); | ||
|
||
IAuthenticationResult result = cca.acquireToken(parameters).get(); | ||
IAuthenticationResult result2 = cca.acquireToken(parameters).get(); | ||
|
||
//OBO flow should perform an internal cache lookup, so similar parameters should only cause one HTTP client call | ||
Avery-Dunn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
assertEquals(result.accessToken(), result2.accessToken()); | ||
verify(httpClientMock, times(1)).send(any()); | ||
} | ||
|
||
@Test | ||
void OnBehalfOf_TenantOverride() throws Exception { | ||
DefaultHttpClient httpClientMock = mock(DefaultHttpClient.class); | ||
|
||
ConfidentialClientApplication cca = | ||
ConfidentialClientApplication.builder("clientId", ClientCredentialFactory.createFromSecret("password")) | ||
.authority("https://login.microsoftonline.com/tenant") | ||
.instanceDiscovery(false) | ||
Avery-Dunn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.validateAuthority(false) | ||
.httpClient(httpClientMock) | ||
.build(); | ||
|
||
HashMap<String, String> tokenResponseValues = new HashMap<>(); | ||
tokenResponseValues.put("access_token", "accessTokenFirstCall"); | ||
|
||
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(tokenResponseValues))); | ||
OnBehalfOfParameters parameters = OnBehalfOfParameters.builder(Collections.singleton("scopes"), new UserAssertion(TestHelper.signedAssertion)).build(); | ||
|
||
//The two acquireToken calls have the same parameters... | ||
IAuthenticationResult resultAppLevelTenant = cca.acquireToken(parameters).get(); | ||
IAuthenticationResult resultAppLevelTenantCached = cca.acquireToken(parameters).get(); | ||
//...so only one token should be added to the cache, and the mocked HTTP client's "send" method should only have been called once | ||
assertEquals(1, cca.tokenCache.accessTokens.size()); | ||
assertEquals(resultAppLevelTenant.accessToken(), resultAppLevelTenantCached.accessToken()); | ||
verify(httpClientMock, times(1)).send(any()); | ||
|
||
tokenResponseValues.put("access_token", "accessTokenSecondCall"); | ||
|
||
when(httpClientMock.send(any(HttpRequest.class))).thenReturn(TestHelper.expectedResponse(200, TestHelper.getSuccessfulTokenResponse(tokenResponseValues))); | ||
parameters = OnBehalfOfParameters.builder(Collections.singleton("scopes"), new UserAssertion(TestHelper.signedAssertion)).tenant("otherTenant").build(); | ||
|
||
//Overriding the tenant parameter in the request should lead to a new token call being made... | ||
IAuthenticationResult resultRequestLevelTenant = cca.acquireToken(parameters).get(); | ||
IAuthenticationResult resultRequestLevelTenantCached = cca.acquireToken(parameters).get(); | ||
//...which should be different from the original token, and thus the cache should have two tokens created from two HTTP calls | ||
assertEquals(2, cca.tokenCache.accessTokens.size()); | ||
assertEquals(resultRequestLevelTenant.accessToken(), resultRequestLevelTenantCached.accessToken()); | ||
assertNotEquals(resultAppLevelTenant.accessToken(), resultRequestLevelTenant.accessToken()); | ||
verify(httpClientMock, times(2)).send(any()); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,19 +3,38 @@ | |
|
||
package com.microsoft.aad.msal4j; | ||
|
||
import com.nimbusds.jose.*; | ||
import com.nimbusds.jose.crypto.RSASSASigner; | ||
import com.nimbusds.jose.jwk.RSAKey; | ||
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator; | ||
|
||
import java.io.File; | ||
import java.io.FileWriter; | ||
import java.io.IOException; | ||
import java.net.URISyntaxException; | ||
import java.nio.file.Files; | ||
import java.nio.file.Paths; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
|
||
class TestHelper { | ||
|
||
static String readResource(Class<?> classInstance, String resource) throws IOException, URISyntaxException { | ||
return new String( | ||
Files.readAllBytes( | ||
Paths.get(classInstance.getResource(resource).toURI()))); | ||
//Signed JWT which should be enough to pass the parsing/validation in the library, useful if a unit test needs an | ||
// assertion but that is not the focus of the test | ||
static String signedAssertion = generateToken(); | ||
private static final String successfulResponseFormat = "{\"access_token\":\"%s\",\"id_token\":\"%s\",\"refresh_token\":\"%s\"," + | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: successfulUserTokenResponseFormat |
||
"\"client_id\":\"%s\",\"client_info\":\"%s\"," + | ||
"\"expires_on\": %d ,\"expires_in\": %d," + | ||
"\"token_type\":\"Bearer\"}"; | ||
|
||
static String readResource(Class<?> classInstance, String resource) { | ||
try { | ||
return new String(Files.readAllBytes(Paths.get(classInstance.getResource(resource).toURI()))); | ||
} catch (IOException | URISyntaxException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
static void deleteFileContent(Class<?> classInstance, String resource) | ||
|
@@ -27,4 +46,55 @@ static void deleteFileContent(Class<?> classInstance, String resource) | |
fileWriter.write(""); | ||
fileWriter.close(); | ||
} | ||
|
||
static String generateToken() { | ||
bgavrilMS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
try { | ||
RSAKey rsaJWK = new RSAKeyGenerator(2048) | ||
.keyID("kid") | ||
.generate(); | ||
JWSObject jwsObject = new JWSObject( | ||
new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(), | ||
new Payload("payload")); | ||
|
||
jwsObject.sign(new RSASSASigner(rsaJWK)); | ||
|
||
return jwsObject.serialize(); | ||
} catch (JOSEException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
|
||
//Maps various values to the successfulResponseFormat string to create a valid token response | ||
static String getSuccessfulTokenResponse(HashMap<String, String> responseValues) { | ||
//Will default to expiring in one hour if expiry time values are not set | ||
long expiresIn = responseValues.containsKey("expires_in") ? | ||
Long.parseLong(responseValues.get("expires_in")) : | ||
3600; | ||
long expiresOn = responseValues.containsKey("expires_on") | ||
? Long.parseLong(responseValues.get("expires_0n")) : | ||
(System.currentTimeMillis() / 1000) + expiresIn; | ||
|
||
return String.format(successfulResponseFormat, | ||
responseValues.getOrDefault("access_token", "access_token"), | ||
responseValues.getOrDefault("id_token", "id_token"), | ||
bgavrilMS marked this conversation as resolved.
Show resolved
Hide resolved
|
||
responseValues.getOrDefault("refresh_token", "refresh_token"), | ||
responseValues.getOrDefault("client_id", "client_id"), | ||
responseValues.getOrDefault("client_info", "client_info"), | ||
expiresOn, | ||
expiresIn | ||
); | ||
} | ||
|
||
//Creates a valid HttpResponse that can be used when mocking HttpClient.send() | ||
static HttpResponse expectedResponse(int statusCode, String response) { | ||
Map<String, List<String>> headers = new HashMap<>(); | ||
headers.put("Content-Type", Collections.singletonList("application/json")); | ||
|
||
HttpResponse httpResponse = new HttpResponse(); | ||
httpResponse.statusCode(statusCode); | ||
httpResponse.body(response); | ||
httpResponse.addHeaders(headers); | ||
|
||
return httpResponse; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not tested.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added tests in the latest commit, essentially just a copy/paste of the OBO tests but use the type of Parameters that would go through this code.