Spotify 节点网络 api - 多用户问题

Spotify node web api - trouble with multiple users

我正在开发一个使用 Spotify Node web API and having trouble when multiple users login into my application. I am successfully able to go through authentication flow and get the tokens and user ID after a user logs in. I am using the Authorization Code to authorize user (since I would like to get refresh tokens after expiration). However, the current problem is that getUserPlaylists function described here 的应用程序(仅供参考,如果第一个参数是 undefined,它将 return 经过身份验证的用户的播放列表)[=51= 最近通过身份验证的用户的播放列表,而不是当前使用该应用程序的用户的播放列表。

示例 1: 如果用户 A 登录到应用程序,它将获得其播放列表。如果用户 B 登录到应用程序,它还会看到自己的播放列表。但是,如果用户 A 刷新页面,则用户 A 会看到用户 B 的播放列表(而不是用户 A 自己的播放列表)。

示例2:用户A登录,用户B只要转到app/myplaylists路由就可以看到用户A的播放列表。

我的猜测是,这部分代码有问题

    spotifyApi.setAccessToken(access_token);
    spotifyApi.setRefreshToken(refresh_token);

最新的用户令牌覆盖之前的任何用户,因此之前的用户正在失去执行诸如查看自己的播放列表等操作的授权。

我知道我可以在不使用 Spotify 节点的情况下使用令牌 API 并且只使用令牌来发出请求,这应该没问题,但是,仍然能够使用节点 API 并处理多个用户会很棒。

这是最有可能有问题的代码部分:

export const createAuthorizeURL = (
    scopes = SCOPE_LIST,
    state = 'spotify-auth'
) => {
    const authUrl = spotifyApi.createAuthorizeURL(scopes, state);

    return {
        authUrl,
        ...arguments
    };
};

export async function authorizationCodeGrant(code) {
    let params = {
        clientAppURL: `${APP_CLIENT_URL || DEV_HOST}/app`
    };

    try {
        const payload = await spotifyApi.authorizationCodeGrant(code);
        const { body: { expires_in, access_token, refresh_token } } = payload;

        spotifyApi.setAccessToken(access_token);
        spotifyApi.setRefreshToken(refresh_token);

        params['accessToken'] = access_token;
        params['refreshToken'] = refresh_token;

        return params;
    } catch (error) {
        return error;
    }

    return params;
}

export async function getMyPlaylists(options = {}) {
    try {
        // if undefined, should return currently authenticated user
        return await spotifyApi.getUserPlaylists(undefined, options);
    } catch (error) {
         return error;
    }
}

在此方面提供任何帮助,我们将不胜感激。我对自己正在做的事情感到非常兴奋,所以如果有人能帮我找到问题,那将意义重大……

你走在正确的轨道上。但是,当您设置访问令牌和刷新令牌时,您是在为整个应用程序设置它,所有调用您的服务器的用户都将使用它。不理想。

下面是 Node 中授权代码流的工作示例:https://glitch.com/edit/#!/spotify-authorization-code

如您所见,它使用 SpotifyWebApi 的一般实例来处理身份验证,但它会为每个对用户数据的请求实例化一个新的 loggedInSpotifyApi,因此您获取用户的数据谁要的

如果您想使用上面的示例,您可以开始编辑 "remix" 并创建您自己的项目副本。

祝您黑客愉快!