I am trying to generate an access token via a PKCE flow to call the Microsoft Graph API.
I am following this msdoc : Microsoft identity platform and OAuth 2.0 authorization code flow – Microsoft Entra | Microsoft Docs
But I am getting error like below:
AADSTS501491: Invalid size of Code_Challenge parameter.
To generate code_challenge, I am using below PHP code in reference to the above documentation.
The code_challenge generated by my code is 43 characters, which is the same string as the value generated by this tool using the same code_verifier, what is wrong?
For testing, I directly stored the value generated by the above tool in $codeChallenge in the following code and got the same error.
public function generateUrl()
{
// cf. https://datatracker.ietf.org/doc/html/rfc7636#section-4
$codeVerifier = $this->generateCodeVerifier();
$codeChallenge = $this->generateCodeChallenge($codeVerifier);
$fields = [
'tenant' => $tenantId,
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'response_mode' => 'query',
'scope' => 'User.Read Directory.Read.All Group.Read.All GroupMember.Read.All',
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
];
$baseUrl = "https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize";
return $baseUrl . '?' . http_build_query($fields);
}
private function generateCodeVerifier() {
$randomString = random_bytes(32);
$urlSafeString = strtr(base64_encode($randomString), '+/', '-_');
return rtrim($urlSafeString, '=');
}
private function generateCodeChallenge($codeVerifier) {
$hashedVerifier = hash('sha256', $codeVerifier, true);
$urlSafeString = strtr(base64_encode($hashedVerifier), '+/', '-_');
return rtrim($urlSafeString, '=');
}
sko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.