我在 Azure AD 中创建了一个 SPA 应用程序,并尝试通过邮递员的 PKCE 流生成访问令牌。
我正在关注此 msdoc:Microsoft 身份平台和 OAuth 2.0 授权代码流程 - Microsoft Entra |微软文档
为了生成代码,我使用下面的授权端点,如上面文档中提到的
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=myclientid
&response_type=code
&redirect_uri=myredirecturi
&response_mode=query
&scope=https://graph.microsoft.com/.default
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256
但是我收到如下错误:
AADSTS501491: Invalid size of Code_Challenge parameter.
code_challenge 参数的有效值是多少以及如何生成它?
此错误 “Code_Challenge 参数的大小无效。” 通常在
code_challenge
无效时发生。确保生成有效的代码_挑战。
要生成
code_challenge
,您可以使用这个工具,如下所示:
我在我的环境中尝试并成功获取了代码值,包括上面的代码挑战值:
确保包含
origin
标题,如下所示:
包含所有必需的参数后,我能够通过 Postman 的 PKCE 流程成功生成访问令牌,如下所示:
$this->code_challenge = hash("sha256", random_bytes("96"));
$code_challenge = substr($this->code_challenge, 0, 43)
# Set the length of the code verifier
$codeVerifierLength = 64
# Set the code verifier and code challenge
$codeVerifier = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count $codeVerifierLength | ForEach-Object {[char]$_})
$codeChallenge = [System.Convert]::ToBase64String([System.Security.Cryptography.SHA256]::Create().ComputeHash([System.Text.Encoding]::UTF8.GetBytes($codeVerifier)))
$codeChallenge = $codeChallenge -replace "\+","-" -replace "/","_" -replace "=",""
# Output the code verifier
Write-Output "Code Verifier : $codeVerifier"
# Output the code challenge
Write-Output "Code Challenge: $codeChallenge"
# Set the request parameters
$params = @{
client_id = $clientId
redirect_uri = $redirectUri
response_type = "code"
response_mode = "query"
resource = $resource
scope = $scope
code_challenge = $codeChallenge
code_challenge_method = "S256"
}
# Build the authorization URL
$authUrl = $authEndpoint + "?" + $(($params.GetEnumerator() | ForEach-Object { "$($_.Name)=$($_.Value)" }) -join "&").tostring()