ios - Spotify PKCE 授权流程返回 "code_verifier was incorrect"

标签 ios swift oauth-2.0 spotify pkce

我一直在关注Spotify API's Authentication Guide使用 PKCE 对我的应用程序进行身份验证。
截至目前,我使用的是假人 验证码 带有预先计算的 挑战 用于调试。这些值是使用多个在线工具(SHA256SHA256base64urlbase64url)计算得出的,并且与我用 Swift 编写的散列/编码函数返回的值相匹配。随意使用上面的链接来验证这些。

let verifier = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
let challenge = "66d34fba71f8f450f7e45598853e53bfc23bbd129027cbb131a2f4ffd7878cd0"
let challengeBase64URL = "NjZkMzRmYmE3MWY4ZjQ1MGY3ZTQ1NTk4ODUzZTUzYmZjMjNiYmQxMjkwMjdjYmIxMzFhMmY0ZmZkNzg3OGNkMA"
我在步骤 2 中使用 ASWebAuthenticationSession 发出初始请求,如下所示:
var components = URLComponents()
components.scheme = "https"
components.host = "accounts.spotify.com"
components.path = "/authorize"
components.queryItems = [
    URLQueryItem(name: "client_id", value: SpotifyClientID),
    URLQueryItem(name: "response_type", value: "code"),
    URLQueryItem(name: "redirect_uri", value: SpotifyRedirectURL.absoluteString),
    URLQueryItem(name: "code_challenge_method", value: "S256"),
    URLQueryItem(name: "code_challenge", value: challenge),
    URLQueryItem(name: "state", value: "testing-state"),
    URLQueryItem(name: "scope", value: "user-follow-read")
]
let urlString = components.url!.absoluteString

guard let authURL = URL(string: urlString) else { return }
print(authURL)
let authSession = ASWebAuthenticationSession(url: authURL, callbackURLScheme: callbackScheme, completionHandler: handleLoginResponse)
authSession.presentationContextProvider = self
authSession.prefersEphemeralWebBrowserSession = true
authSession.start()
handleLoginResponse ,我在步骤 3 中解析响应并使用 Alamofire 为步骤 4 发出网络请求:
guard let items = URLComponents(string: callbackURL?.absoluteString ?? "").queryItems else { return }
let authCode = items[0].value!
let endpoint = "https://accounts.spotify.com/api/token"

let headers = HTTPHeaders(["Content-Type": "application/x-www-form-urlencoded"])
let parameters: [String: String] = [
    "client_id": SpotifyClientID,
    "grant_type": "authorization_code",
    "code": authCode,
    "redirect_uri": SpotifyRedirectURL.absoluteString,
    "code_verifier": verifier!
]
AF.request(endpoint,
           method: .post,
           parameters: parameters,
           encoder: URLEncodedFormParameterEncoder.default,
           headers: headers
).cURLDescription() { description in
    print(description)
}
.responseJSON() { (json) in
    print(json)
}
Alamofire 创建了一个接口(interface)来从 Swift 中发出 cURL 请求,并调用 cURLDescription()让我确切地看到实际的 cURL 命令最终是什么:
$ curl -v \
    -X POST \
    -b "__Host-device_id=AQBHyRKdulrPJU6vY5xlua1xKOZBtBZVcrW9IK-X0LQ_MPj5x3N4mZkF4OzgLMdQwviWUxJ2dY6d49d0QpjG0ayFtCfrhwzG5-g" \
    -H "User-Agent: SpotifyUserGraph/1.0 (hl999.SpotifyUserGraph; build:1; iOS 14.0.0) Alamofire/5.1.0" \
    -H "Accept-Encoding: br;q=1.0, gzip;q=0.9, deflate;q=0.8" \
    -H "Accept-Language: en-US;q=1.0, zh-Hans-US;q=0.9, ko-US;q=0.8" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -d "client_id=e11fb810282946569aab8f89e52f78d5&code=AQC3Lm3KDPFCg3mBjSAiXMyvjdn5GvUJCjjCTQzPhAFe5mLntAHcAeiEufXcCv3Jne2qn345MZxBNiCggO-35mn6AAFsjRlm5lPynyC6clWABSzBK1OdWIynTlf0CiyR8vWYeO54GHHEXBSzj6URKWnAiXuxTUV6n1Axra6Oet8FY6-0jwU0CNGMaB91q1JFXlyl5J9JvrRtrP3s2Ef8Xb5A7gcCzqW6RHRzO0--BKiPHFnprK0SitiLxi-md2aaMnS2aHsRTqvc_NfFcuRpFR05WmSm6Gvkk_9trSBqRvVZYuGs-Ap3-ydVGk7BCqNc3lpbh4Jku6W_930fOg9kI__zRA&code_verifier=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&grant_type=authorization_code&redirect_uri=hl999-spotifyusergraph%3A//spotify-login-callback" \
    "https://accounts.spotify.com/api/token"
这有点难以阅读,但我很确定请求是正确的。
但是,在第 4 步,我总是从服务器收到此错误消息:
error = "invalid_grant";
"error_description" = "code_verifier was incorrect";
在几个小时的过程中,我尝试了很多事情,但仍然无法弄清楚。任何指针将不胜感激。谢谢!

最佳答案

您的问题是 SHA 哈希的原始字节是需要 base64ed 的。我还在开发一个使用 Alamofire 和 Spotify PKCE 的应用程序,但遇到了代码挑战。我所做的是使用 Auth0 documentation 中的一些代码这是为 Swift 3 编写的,并对其进行了修改以与 Swift 5 一起使用:

import Foundation
import CommonCrypto
 
func challenge(verifier: String) -> String {
    
    guard let verifierData = verifier.data(using: String.Encoding.utf8) else { return "error" }
        var buffer = [UInt8](repeating: 0, count:Int(CC_SHA256_DIGEST_LENGTH))
 
        verifierData.withUnsafeBytes {
            CC_SHA256($0.baseAddress, CC_LONG(verifierData.count), &buffer)
        }
    let hash = Data(_: buffer)
    print(hash)
    let challenge = hash.base64EncodedData()
    return String(decoding: challenge, as: UTF8.self)
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "_")
        .replacingOccurrences(of: "=", with: "")
        .trimmingCharacters(in: .whitespaces)
}
print(challenge(verifier: "ExampleVerifier"))

希望这对您有所帮助并祝您好运!

关于ios - Spotify PKCE 授权流程返回 "code_verifier was incorrect",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63482575/

相关文章:

ios - 0Auth2 : when do you use the refresh token to get a new access token? 过期前还是过期后?

java - 如何在java中使用google plus api在用户的Streams中发帖

ios - 横向 iPhone X 上的全屏 UICollectionViewCell 问题

ios - 如何通过swift获取字符串中的换行频率

ios - 没有匹配函数调用 'dot' 和 'reflect'

ios - swift - Playground : mathematical functions ambiguous use of tan

iOS - @IBDesignable UITextField 子类在 IB 中正确显示,但在设备上不正确

objective-c - Swift:对具有相同选择器的对象进行类型转换

ios - 未使用结构

c# - 如何在 ASP.NET Core 中为 Azure AD 请求正确的访问 token 来访问 Microsoft Graph