gpt4 book ai didi

node.js - 尝试使用访问 token 访问 Spotify Web api 时收到 401

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:21 25 4
gpt4 key购买 nike

我正在使用 Spotify 策略和 Passport Js 进行身份验证。然后,我想使用 spotify-web-api-node 包装器库来调用 Spotify 的数据。但是,使用从身份验证中获得的访问 token 和刷新 token 进行后续调用是行不通的。我在尝试调用 Spotify 获取用户特定数据时收到 401 - 未经授权。

我尝试使用刷新 token 和访问 token 实例化 SpotifyWebApiObject。尽管我可以在库中看到它只需要访问 token 即可进行调用。我也尝试过登录和注销以获取新的 token 集。

passport.use(new SpotifyStrategy({
clientID: keys.spotifyClientID,
clientSecret: keys.spotifyClientSecret,
callbackURL: '/auth/spotify/callback',
proxy: true
}, async (accessToken, refreshToken, profile, done) => {


const spotifyId = profile.id;
const name = profile.displayName;
const email = profile.emails[0].value;

console.log(profile.id)
const existingUser = await User.findOne({ spotifyId: profile.id });

if (existingUser) {
let userCredentials = await UserCredential.findOne({ userId: spotifyId });

if (!userCredentials) {
return await new UserCredential({ userId: spotifyId, name, accessToken, refreshToken }).save();
}
console.log('always get existing user')
userCredentials.accessToken = accessToken;
userCredentials.refreshToken = refreshToken;
return done(null, existingUser);
}


const user = await new User({ spotifyId }).save();
await new UserCredential({ userId: spotifyId, name, accessToken, refreshToken }).save();

done(null, user);
}));

一旦它们存储在数据库中。我查找用户并使用相应的访问 token 和刷新 token 。

const getPlaylists = async (user) => {

let spotifyData = await initiateSpotifyWebApi(user);

spotifyData.getUserPlaylists(user.spotifyId).then((res) => {
console.log('response is ===', res)
}).catch((err) => console.error(err));

}

async function initiateSpotifyWebApi(user) {

const creds = await UserCredential.findOne({ userId: user.spotifyId });
const apiCaller = setUpApiObj(creds.refreshToken, creds.accessToken);

return apiCaller
}

function setUpApiObj(refreshTok, accessTok) {
const spotifyApi = new SpotifyWebApi({
accessToken: accessTok,
refreshToken: refreshTok
});
return spotifyApi;
}
getUserPlaylist()

返回错误

{ [WebapiError: Unauthorized] name: 'WebapiError', message: 'Unauthorized', statusCode: 401 }

知道为什么我无法按照我尝试的方式使用这个库访问 api 吗?

谢谢

最佳答案

有几件事需要检查。这就是我想到的。如果我走错了路,请纠正我,我会尽力提供进一步的帮助。

  1. 当您通过 Spotify 进行身份验证时,请检查您的“范围”。您需要有正确的范围才能对 API 执行不同的操作。参见这里:https://developer.spotify.com/documentation/general/guides/authorization-guide/

  2. 如果您收到 401,请使用刷新 token (我可以看到您正在存储它)自动请求、检索并覆盖您当前的 AccessToken,然后再次执行请求。

关于node.js - 尝试使用访问 token 访问 Spotify Web api 时收到 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55481516/

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