Spotify Web API 授权问题 [重复]
Posted
技术标签:
【中文标题】Spotify Web API 授权问题 [重复]【英文标题】:Spotify Web API authorization issue [duplicate] 【发布时间】:2021-09-22 22:45:19 【问题描述】:我对 RectJs 和 Node 比较陌生,我正在尝试使用他们的 API 从 Spotify 获取一些信息。我从中获得一些代码的 Github 存储库有一个 html 文件以及用于授权的节点文件。当我使用该 HTML 来单击按钮并触发调用时,授权和其他东西工作正常,但是当我尝试使用我的 React 服务器调用 Spotify 的授权端点时,它给了我这个错误:
在 'https://accounts.spotify.com/authorize?response_type=code&client_id=3054cb711c3c4fc48cff3458cdaddea2&scope=user-read-private%20user-read-email&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback&state= 访问 XMLHttpRequest J9lrQajWgCnjJy0q'(从 'http://localhost:8888/login' 重定向)来自原点'http://localhost:3000' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否'访问-Control-Allow-Origin' 标头存在于请求的资源上。
ReactJS 服务器:
import React, Component from 'react';
import './Spotify.scss';
import axios from 'axios';
export default class First extends React.Component
handlelogin()
axios
.get('http://localhost:8888/login',
headers:
'Access-Control-Allow-Origin': '*',
)
.then()
.catch(err =>
console.error(err);
);
render()
return(
<div className="container">
<div className="info">
<div className="logo"><p>Spotify</p></div>
<button className="btn" name="login" onClick= () => this.handlelogin()> Log-in to Spotify </button>
</div>
</div>
);
节点服务器:
var express = require('express');
var request = require('request');
var cors = require('cors');
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
var SpotifyWebApi = require('spotify-web-api-node');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded( extended: false ));
var usersid='';
var stateKey = 'spotify_auth_state';
var client_id = '3054cb711c3c4fc48cff3458cdaddea2';
var client_secret = 'b43bf5c8fe0040829f0029ac301a5ea7';
var redirect_uri = 'http://localhost:8888/callback';
var spotifyApi = new SpotifyWebApi(
clientId: '3054cb711c3c4fc48cff3458cdaddea2',
clientSecret: 'b43bf5c8fe0040829f0029ac301a5ea7',
redirectUri: 'http://www.localhost:8888'
);
var generateRandomString = function(length)
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
;
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
app.get('/login', function(req, res)
console.log('ABCD');
var state = generateRandomString(16);
res.cookie(stateKey, state);
// your application requests authorization
var scope = 'user-read-private user-read-email';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify(
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
));
);
app.get('/callback', function(req, res)
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState)
res.redirect('/#' +
querystring.stringify(
error: 'state_mismatch'
));
else
res.clearCookie(stateKey);
var authOptions =
url: 'https://accounts.spotify.com/api/token',
form:
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
,
headers:
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
,
json: true
;
request.post(authOptions, function(error, response, body)
if (!error && response.statusCode === 200)
var access_token = body.access_token,
refresh_token = body.refresh_token;
tokenuse = access_token;
spotifyApi.setAccessToken(access_token);
var options =
url: 'https://api.spotify.com/v1/me',
headers: 'Authorization': 'Bearer ' + access_token ,
json: true
;
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body)
console.log(body);
userid = body.id;
usersid = body.id;
);
// we can also pass the token to the browser to make requests from there
res.redirect('/#' +
querystring.stringify(
access_token: access_token,
refresh_token: refresh_token
));
else
res.redirect('/#' +
querystring.stringify(
error: 'invalid_token'
));
);
);
app.get('/refresh_token', function(req, res)
var refresh_token = req.query.refresh_token;
var authOptions =
url: 'https://accounts.spotify.com/api/token',
headers: 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) ,
form:
grant_type: 'refresh_token',
refresh_token: refresh_token
,
json: true
;
request.post(authOptions, function(error, response, body)
if (!error && response.statusCode === 200)
var access_token = body.access_token;
token = body.access_token;
res.send(
'access_token': access_token
);
);
);
console.log('Listening on 8888');
app.listen(8888);```
【问题讨论】:
您顺便发布了您的客户机密。我会小心分享的! 【参考方案1】:您不应该将它们重定向到 Spotify.. 例如:
querystring.stringify(
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
));
您应该从后端请求 spotify,然后使用应用程序中返回的结果。
【讨论】:
以上是关于Spotify Web API 授权问题 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
spotify-web-api-node - WebapiError:未经授权
spotify web api授权码授予thelinmichael / spotify-web-api-java android