gpt4 book ai didi

javascript - Spotify PKCE code_verifier 不正确

转载 作者:行者123 更新时间:2023-12-04 14:12:33 31 4
gpt4 key购买 nike

我很高兴听到我现在可以使用 Spotify Web API,而无需通过 PKCE 使用后端应用程序。不幸的是,我似乎有某种误解,无法让它发挥作用。
在此过程中,我可能会犯一些小错误,但我做了一次但无济于事,我把石板擦干净并再次尝试,但仍然没有运气。由此我认为我一定是误解了 documentation .
我会解释我在做什么,希望这里有人能指出我遗漏了什么或做错了什么。我假设我有一个基本的概念误解。
我首先使用名为 crypto-random-string 的 npm 包生成一个加密随机字符串。我将它存储在浏览器的本地存储中,然后使用 js-sha256 对其进行哈希处理,然后使用另一个名为 base64url 的 npm 包对其进行编码。

    let verifier = cryptoRandomString({length: 50})
window.localStorage.setItem('verifier', verifier)

let params = {
client_id: '[MY CLIENT ID]',
response_type: 'code',
redirect_uri: 'http://localhost:3000/callback',
code_challenge_method: 'S256',
code_challenge: base64url(sha256(verifier))
}

let endpoint = new URL('https://accounts.spotify.com/authorize');
endpoint.search = new URLSearchParams(params);

window.location = endpoint.toString();
从这里,我使用正确的 url 参数重定向到/authorize 端点。我已经成功地做到了这一点,然后被相应地重定向到我提供的redirect_uri,在那里我从 url 参数中获取给定的代码。
在这一点上,我尝试使用 client_id、grant_type、我从 url 参数中获得的代码、我的 redirect_uri 和本地存储的 code_verifier 获取到/api/token 端点。
    let params = new URLSearchParams(window.location.search);
console.log(params.get('code'));

let newParams = {
client_id: '[MY CLIENT ID]',
grant_type: 'authorization_code',
code: params.get('code'),
redirect_uri: 'http://localhost:3000/callback',
code_verifier: window.localStorage.getItem('verifier')
}

let endpoint = new URL('https://accounts.spotify.com/api/token');

endpoint.search = new URLSearchParams(newParams);

fetch(endpoint.toString(), {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(data => data.json()).then(console.log)
此时,在我两次尝试后,我收到了错误:
{ error: "invalid_grant", error_description: "code_verifier was incorrect" }
有什么我明显做错了吗?该错误使我相信就 code_verifier 的实际生成而言,我做错了什么,但我不知道该问题可能是什么。

最佳答案

Spotify 论坛上有人指给我 this回答。不确定为什么,但按以下方式进行编码确实有效:

    async function sha256(plain) {
const encoder = new TextEncoder()
const data = encoder.encode(plain)

return window.crypto.subtle.digest('SHA-256', data)
}

function base64urlencode(a){
return btoa(String.fromCharCode.apply(null, new Uint8Array(a))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

const hashed = await sha256(verifyCode)
const codeChallenge = base64urlencode(hashed)

关于javascript - Spotify PKCE code_verifier 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63095557/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com