go - Golang sha256 哈希不满足 okta 代码挑战
问题描述
我正在使用 golang 来实现针对 Okta 的 PKCE 身份验证流程。Okta 需要一个至少包含 43 个字符的 url 安全字符串(验证者),然后计算一个 sha256 哈希,该哈希以 base64 URL 编码(质询)的形式发送。Okta PKCE 流程
我生成一个随机验证器。这是一个示例:aAOzSsxfONaAauKYKRABWUfZLFgVFZqgbJRaArwKAzhzEWurUAhDyzcTkSKLClFL
要生成 base64 编码的 sha256 和:
hasher := sha256.New()
hasher.Write([]byte(login.CodeVerifier))
codeChallenge := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
当给出verifier
上面的示例时,产生了一个挑战:1XvaG5_-p9OPfxH9yeLmSWu5zGHxW6Pjq_HrdSsI-kk=
然而,在完成对/token
端点的 POST 后,总是返回错误:
{
"error": "invalid_grant",
"error_description": "PKCE verification failed."
}
这是 POST 到的逻辑/token
:
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
log.Debug().Msgf("callback code:%s state:%s verifier:%s", code, state, loginCache[state])
values := url.Values{}
values.Set("grant_type", "authorization_code")
values.Set("client_id", clientID)
values.Set("redirect_uri", redirectURI)
values.Set("code", code)
values.Set("code_verifier", loginCache[state])
request, _ := http.NewRequest("POST", oktaTokenURL, strings.NewReader(values.Encode()))
request.URL.RawQuery = values.Encode()
request.Header.Set("accept", "application/json")
request.Header.Set("cache-control", "no-cache")
request.Header.Set("content-type", "application/x-www-form-urlencoded")
response, err := http.DefaultClient.Do(request)
解决方案
我对 Golang 不熟悉,但我认为问题在于您使用了错误的函数来进行 bas64 编码。RFC 7636状态
Base64url Encoding
Base64 encoding using the URL- and filename-safe character set
defined in Section 5 of [RFC4648], with all trailing '='
characters omitted (as permitted by Section 3.2 of [RFC4648]) and
without the inclusion of any line breaks, whitespace, or other
additional characters. (See Appendix A for notes on implementing
base64url encoding without padding.)
查看 Go中的base64 文档,var RawStdEncoding = StdEncoding.WithPadding(NoPadding)
应该会输出正确的格式。
RawStdEncoding 是标准的原始、未填充的 base64 编码,如 RFC 4648 第 3.2 节中所定义。这与 StdEncoding 相同,但省略了填充字符。
推荐阅读
- python - 无法使用 pip gettting 后端 BackendUnavailable 安装 python jsonschema 包
- backend - Strapi 管理页面未在新电脑中加载
- sql-server - 使用 Sqlbulkcopy 将数据从 Sql Server 导出到 Excel
- php - jQuery Ajax 请求无法将所有带有 SQL 查询的数据带到字段中
- perl - Perl:如何在目录及其所有父目录中搜索名为“.cfg”的文件
- php - Symfony 5 - 注意:由于角色,用户创建表单中的数组到字符串转换
- reactjs - React 路由器不适用于 AWS Amplify
- vue.js - Paystack回调方法中的Axios发布调用未触发
- performance - 如何知道 ComputeShader 调度的效率?如果多个调度一个接一个地处理怎么办?
- javascript - 如何在响应式地图中以编程方式缩放到 D3 中的元素?