【发布时间】:2018-06-29 23:32:32
【问题描述】:
我正在尝试设置我的应用程序,以便可以使用 Spotify API。他们的 API 需要一个授权令牌以及每个请求,并且这个令牌在每个用户会话中都不同。我已经使用“passport-spotify”模块(详情如下)成功实现了 OAuth2 登录,并拥有了我目前存储在我的数据库中的令牌。一旦它在数据库中,它也可以在我的 Redux 存储中使用。
有效的护照策略:
const spotifyConfig = {
clientID: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
callbackURL: process.env.SPOTIFY_CALLBACK
}
const strategy = new SpotifyStrategy(spotifyConfig, (accessToken, refreshToken, profile, done) => {
const spotifyId = profile.id
const name = profile.displayName
const email = profile.emails[0].value
User.find({where: {spotifyId}})
.then(foundUser => (foundUser
? foundUser.update({accessToken, refreshToken}).then(() => done(null, foundUser))
: User.create({name, email, spotifyId, accessToken, refreshToken})
.then(createdUser => done(null, createdUser))
))
.catch(done)
})
passport.use(strategy)
router.get('/', passport.authenticate('spotify', {scope: ['user-read-email'], showDialog: true}))
router.get('/callback', passport.authenticate('spotify', {
successRedirect: '/home',
failureRedirect: '/login'
}))
我目前坚持的是如何设置我的 API 请求,以便在每次调用时访问该令牌。 'spotify-web-api-node' 节点模块有一个 setCredentials 方法,但我不知道如何访问令牌。
半功能 API 调用(它发出 API 请求但给了我未经授权的 403):
const SpotifyWebApi = require('spotify-web-api-node');
const spotifyApi = new SpotifyWebApi();
spotifyApi.setCredentials({
clientId: 'my client id',
clientSecret: 'my client secret',
redirectUri: 'http://localhost:8888/auth/spotify/callback',
refreshToken: 'cant figure out how to properly include this',
accessToken: 'and this.',
});
export function searchMetallica(){
return spotifyApi.searchArtists('Metallica')
.then(function(data) {
console.log(data.body);
}, function(err) {
console.error(err);
});
}
我希望这不是一个新手问题。提前致谢。
【问题讨论】:
标签: javascript oauth-2.0 authorization spotify access-token