所以我是使用OAuth的新手,老实说我很想完成这项工作。我查看了Spotify's Authorization code的文档,还找到了我用过的wrapper for node。
我希望能够通过spotify登录用户,并从那里对Spotify API进行API调用。
通过一个示例,我最终获得了/callback
路由的代码,该路由在用户被授予访问权限后被点击,Spotify Accounts服务会将您重定向到那里:
app.get('/callback', (req, res) => {
const { code, state } = req.query;
const storedState = req.cookies ? req.cookies[STATE_KEY] : null;
if (state === null || state !== storedState) {
res.redirect('/#/error/state mismatch');
} else {
res.clearCookie(STATE_KEY);
spotifyApi.authorizationCodeGrant(code).then(data => {
const { expires_in, access_token, refresh_token } = data.body;
// Set the access token on the API object to use it in later calls
spotifyApi.setAccessToken(access_token);
spotifyApi.setRefreshToken(refresh_token);
// use the access token to access the Spotify Web API
spotifyApi.getMe().then(({ body }) => {
console.log(body);
});
res.redirect(`/#/user/${access_token}/${refresh_token}`);
}).catch(err => {
res.redirect('/#/error/invalid token');
});
}
});
所以上面,在请求结束时,令牌被传递给浏览器以从那里发出请求:res.redirect('/#/user/${access_token}/${refresh_token}');
如果在那里重定向,我想将用户重定向到可以搜索艺术家的表单。我是否需要这样以某种方式始终在令牌周围传递令牌?我如何将用户重定向到那里?我试着简单地渲染一个新页面并在那里传递params但它没有用。
答案 0 :(得分:1)
您可以将令牌存储在各种位置,包括查询参数或Cookie - 但我建议您使用localstorage。当您的前端加载/#/user/${access_token}/${refresh_token}
路由时,您可以获取值并将其存储在localstorage中(例如localstorage.set('accessToken', accessToken)
),并在以后需要调用API时检索它们。