我正在创建一个网络应用程序,告诉任何用户他们在 spotify 上的顶级艺术家/曲目。 如果我使用我正在使用的相同 clientId 的帐户登录,它就可以工作。但是,如果我使用另一个帐户登录,则会出现此错误:
有些事情我不太明白...之后我在我的开发人员仪表板中注册了另一个用户,现在它可以工作了,但我如何做到这一点,以便任何人都可以访问该应用程序而无需我手动注册他们的帐户?
这是我直接从 spotify 的官方 web api 示例中获取并进行了一些更改的代码:
script.ts
import { redirectToAuthCodeFlow, getAccessToken } from "./authCodeWithPkce";
const clientId = "*client id*";
const params = new URLSearchParams(window.location.search);
const code = params.get("code");
if (!code) {
redirectToAuthCodeFlow(clientId);
} else {
const accessToken = await getAccessToken(clientId, code);
const profile = await fetchProfile(accessToken);
populateUI(profile);
}
async function fetchProfile(code: string): Promise<UserProfile> {
const result = await fetch(
"https://api.spotify.com/v1/me/top/tracks?time_range=long_term&limit=10",
{
method: "GET",
headers: { Authorization: `Bearer ${code}` },
}
);
return await result.json();
}
function populateUI(profile: UserProfile) {
document.getElementById("displayName")!.innerText =
profile.items[0].album.album_type;
}
authCodeWithPkce.ts
export async function redirectToAuthCodeFlow(clientId: string) {
const verifier = generateCodeVerifier(128);
const challenge = await generateCodeChallenge(verifier);
localStorage.setItem("verifier", verifier);
const params = new URLSearchParams();
params.append("client_id", clientId);
params.append("response_type", "code");
params.append("redirect_uri", "http://localhost:3000/callback");
params.append("scope", "user-top-read");
params.append("code_challenge_method", "S256");
params.append("code_challenge", challenge);
document.location = `https://accounts.spotify.com/authorize?${params.toString()}`;
}
export async function getAccessToken(clientId: string, code: string) {
const verifier = localStorage.getItem("verifier");
const params = new URLSearchParams();
params.append("client_id", clientId);
params.append("grant_type", "authorization_code");
params.append("code", code);
params.append("redirect_uri", "http://localhost:3000/callback");
params.append("scope", "user-top-read");
params.append("code_verifier", verifier!);
const result = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params,
});
const { access_token } = await result.json();
return access_token;
}
function generateCodeVerifier(length: number) {
let text = "";
let possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
async function generateCodeChallenge(codeVerifier: string) {
const data = new TextEncoder().encode(codeVerifier);
const digest = await window.crypto.subtle.digest("SHA-256", data);
return btoa(String.fromCharCode.apply(null, [...new Uint8Array(digest)]))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
如何在不手动注册每个用户的情况下摆脱 403 错误?我在代码中遗漏了什么吗? 提前谢谢你。