无法通过 SPA 的 PKCE 流程生成授权码

问题描述 投票:0回答:4

我在 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 参数的有效值是多少以及如何生成它?

azure-active-directory postman pkce
4个回答
2
投票

此错误 “Code_Challenge 参数的大小无效。” 通常在

code_challenge
无效时发生。确保生成有效的代码_挑战。

要生成

code_challenge
,您可以使用这个工具,如下所示:

enter image description here

我在我的环境中尝试并成功获取了代码值,包括上面的代码挑战值:

enter image description here

确保包含

origin
标题,如下所示:

enter image description here

包含所有必需的参数后,我能够通过 Postman 的 PKCE 流程成功生成访问令牌,如下所示:

enter image description here


0
投票
只需将哈希值精简为 43 个字符即可。那你就好了。例如:

$this->code_challenge = hash("sha256", random_bytes("96")); $code_challenge = substr($this->code_challenge, 0, 43)
    

0
投票
您似乎正在使用S256(SHA256)作为代码质询方法(散列算法到散列代码验证器)。因此请确保 Base 64 编码的 code_challenge 值的长度为 43 个字符。如果有结尾的“=”,请在设置 code_challenge 查询字符串参数值之前将其去掉(这是填充)。


0
投票
这个 PS 代码对我有用。

# 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()
    
© www.soinside.com 2019 - 2024. All rights reserved.