[英]Getting a Spotify access token using only client credentials (Spotify Web API Node)
[英]Getting 401 when trying to access spotify web api with access token
我正在使用帶有護照Js的Spotify策略進行身份驗證。 然后,我想使用spotify-web-api-node包裝器庫進行調用以對數據進行Spotify。 但是,無法使用從身份驗證中獲取的訪問令牌和刷新令牌進行后續調用。 我收到401-嘗試撥打電話以發現用戶特定數據時未經授權。
我嘗試使用刷新令牌和訪問令牌實例化SpotifyWebApiObject。 雖然我可以在庫中看到它,但只需要訪問令牌即可進行調用。 我嘗試登錄和注銷以獲取新的令牌集。
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);
}));
一旦它們被存儲在數據庫中。 我查找用戶,並使用相應的訪問和刷新令牌。
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嗎?
謝謝
幾件事要檢查。 這就是我想到的。 如果我走錯了道路,請糾正我,我會盡力幫助您。
通過Spotify進行身份驗證時,請檢查“范圍” 。 您需要具有正確的作用域才能對API執行不同的操作。 參見此處: https : //developer.spotify.com/documentation/general/guides/authorization-guide/
如果您收到401,請使用刷新令牌(我看到您正在存儲它)自動請求,檢索和覆蓋當前的AccessToken,然后再次執行該請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.