从 Spotify 请求访问令牌时出错 "Only valid bearer authentication supported"

Error "Only valid bearer authentication supported" when requesting access token from Spotify

我正在尝试从 Spotify 获取 oAuth 访问令牌(Guide 中的第 4 步)。

我相信,我按照他们的文档中的描述发送了所有必需的参数,但 Spotify 回复:

"error": {
    "status": 400,
    "message": "Only valid bearer authentication supported"
}

这是我在 node.js 中的请求:

function getToken(code){
    var idAndSecret = config.clientId+':'+config.clientSecret;
    var authString = 'Basic ' + new Buffer(idAndSecret).toString('base64');
    var data = querystring.stringify({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: REDIRECT_URI
    });
    var tokenReq = https.request({
        hostname: 'api.spotify.com',
        path: '/api/token?'+data,
        method: 'POST',
        headers: {
            'Authorization': authString
        }
    }, function(res){
        res.on('data', function(chunk){
            console.log(new Buffer(chunk).toString());
        });
        console.log(res.statusCode, JSON.stringify(res.headers));
    });

    tokenReq.end();
}

我已经检查了我的 clientId、clientSecret、auth-code 和 redirectUri。

这是回应 Header:

{
    "server":"nginx",
    "date":"Sat, 02 Jan 2016 23:58:58 GMT",
    "content-type":"application/json",
    "content-length":"99",
    "connection":"close",
    "www-authenticate":"Bearer realm=\"spotify\",
    error=\"invalid_request\", 
    error_description=\"Only valid bearer authentication supported\"",
    "access-control-allow-origin":"*",
    "access-control-allow-methods":"GET, POST, OPTIONS, PUT, DELETE",
    "access-control-allow-credentials":"true",
    "access-control-max-age":"604800",
    "access-control-allow-headers":"Accept, Authorization, Origin, Content-Type"
}

这是错误的端点:应该是 accounts.spotify.com 而不是 api.spotify.com

然后我得到了状态 500 & 我也修复了这个:

function getToken(code){
    var idAndSecret = config.clientId+':'+config.clientSecret;
    var authString = 'Basic ' + new Buffer(idAndSecret).toString('base64');
    var data = querystring.stringify({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: REDIRECT_URI
    });
    var tokenReq = https.request({
        hostname: 'accounts.spotify.com',
        path: '/api/token',
        method: 'POST',
        headers: {
            'Authorization': authString,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(data)
        }
    }, function(res){
        res.on('data', function(chunk){
            console.log(new Buffer(chunk).toString());
        });
        console.log(res.statusCode, JSON.stringify(res.headers));
    });

    tokenReq.end(data);
}