Skip to content

Ensure Base64URL decoding is used #938

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 1 commit into from
Apr 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private AuthenticationResult createAuthenticationResultFromOauthHttpResponse(
if (!StringHelper.isNullOrBlank(tokens.getIDTokenString())) {
String idTokenJson;
try {
idTokenJson = new String(Base64.getDecoder().decode(tokens.getIDTokenString().split("\\.")[1]), StandardCharsets.UTF_8);
idTokenJson = new String(Base64.getUrlDecoder().decode(tokens.getIDTokenString().split("\\.")[1]), StandardCharsets.UTF_8);
} catch (ArrayIndexOutOfBoundsException e) {
throw new MsalServiceException("Error parsing ID token, missing payload section. Ensure that the ID token is following the JWT format.",
AuthenticationErrorCode.INVALID_JWT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
Expand Down Expand Up @@ -294,4 +296,44 @@ void testExecuteOAuth_Failure() throws SerializeException,

assertThrows(MsalException.class, request::executeTokenRequest);
}

@Test
void testBase64UrlEncoding() throws MalformedURLException, ExecutionException, InterruptedException {
DefaultHttpClient httpClientMock = mock(DefaultHttpClient.class);
ConfidentialClientApplication cca =
ConfidentialClientApplication.builder("clientId", ClientCredentialFactory.createFromSecret("password"))
.authority("https://login.microsoftonline.com/tenant/")
.instanceDiscovery(false)
.validateAuthority(false)
.httpClient(httpClientMock)
.build();

//ID token payloads are parsed to get certain info to create Account and AccountCacheEntity objects, and the library must decode them using a Base64URL decoder.
HashMap<String, String> tokenParameters = new HashMap<>();
tokenParameters.put("preferred_username", "~nameWith~specialChars");
String encodedIDToken = TestHelper.createIdToken(tokenParameters);
try {
//TestHelper.createIdToken() should use Base64URL encoding, so first we prove that the encoded token it produces cannot be decoded with Base64 decoder
Base64.getDecoder().decode(encodedIDToken.split("\\.")[1]);

fail("IllegalArgumentException was expected but not thrown.");
} catch (IllegalArgumentException e) {
//Encoded token should have some "-" characters in it
assertTrue(e.getMessage().contains("Illegal base64 character 2d"));
}

//Now, send that encoded token through the library's token request flow, which will decode it using a Base64URL decoder
HashMap<String, String> responseParameters = new HashMap<>();
responseParameters.put("id_token", encodedIDToken);
responseParameters.put("access_token", "token");
TestHelper.createTokenRequestMock(httpClientMock, TestHelper.getSuccessfulTokenResponse(responseParameters), 200);

OnBehalfOfParameters parameters = OnBehalfOfParameters.builder(Collections.singleton("someScopes"), new UserAssertion(TestHelper.signedAssertion)).build();
IAuthenticationResult result = cca.acquireToken(parameters).get();

//Ensure that the name was successfully parsed out of the encoded ID token
assertNotNull(result.idToken());
assertNotNull(result.account());
assertEquals("~nameWith~specialChars", result.account().username());
}
}