尝试使用访问令牌访问Spotify Web API时获取401

时间:2019-04-02 18:38:09

标签: node.js api web passport.js spotify

我正在使用带有护照Js的Spotify策略进行身份验证。然后,我想使用spotify-web-api-node包装器库进行调用以对数据进行Spotify。但是,无法使用从身份验证中获取的访问令牌和刷新令牌进行后续调用。我收到401-尝试拨打电话以发现用户特定数据时未经授权。

我尝试使用刷新令牌和访问令牌实例化SpotifyWebApiObject。虽然我可以在库中看到它,但只需要访问令牌即可进行调用。我尝试登录和注销以获取新的令牌集。

-v /tmp/foobar:txt:/my/other/path.txt

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

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()

有什么主意,为什么我无法使用此库访问api?

谢谢

1 个答案:

答案 0 :(得分:1)

要检查的事物。这就是我想到的。如果我走错了道路,请纠正我,我会尽力帮助您。

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

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

相关问题