在尝试使用访问令牌访问spotify web api时获取401

问题描述 投票:0回答:1

我正在使用带护照Js的spotify策略进行身份验证。然后,我想使用spotify-web-api-node包装器库来调用数据。但是,使用从后续调用的身份验证中获得的访问和刷新令牌是不行的。我在尝试拨打电话以查明用户特定数据时收到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);
}));

一旦它们存储在db中。我查找用户并使用相应的访问权限和刷新令牌。

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,我正在尝试的方式?

谢谢

node.js api web passport.js spotify
1个回答
1
投票

几件事要检查。这正是我想到的。如果我在错误的轨道上纠正我,我会尽力帮助你。

  1. 通过Spotify进行身份验证时,请检查“范围”。您需要具有正确的范围才能对API执行不同的操作。见这里:https://developer.spotify.com/documentation/general/guides/authorization-guide/
  2. 如果你得到401,使用你的刷新令牌(我可以看到你正在存储它)来自动请求,检索和覆盖你当前的AccessToken,然后再次执行请求。
© www.soinside.com 2019 - 2024. All rights reserved.