首页 > 解决方案 > 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)

标签: gooktapkce

解决方案


我对 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 相同,但省略了填充字符。


推荐阅读