Spotify api检索的访问令牌不起作用

时间:2019-04-02 15:21:09

标签: c# webclient spotify

我正在使用Spotify API创建一个React / C#应用程序,我收到一个访问令牌,但是它不起作用。尝试调用API时出现错误(如下所示)(不知道为什么说“无效的用户名”,因为从未使用过):

  

错误:消息:“无效的用户名”状态:404

code来自身份验证过程中的较早步骤(在我使用节点时起作用,所以我认为那部分是正确的),并且我使用了所有作用域以确保这不是问题playlist-modify-public playlist-modify-private user-read-private user-read-email user-read-playback-state user-read-recently-played

我的C#代码以获取访问令牌:

var spotifyClientId = "id";
var spotifySecret = "secret";

var webClient = new WebClient();

var postparams = new NameValueCollection();
postparams.Add("grant_type", "client_credentials");
postparams.Add("code", code);
postparams.Add("redirect_uri", "http://localhost:8000/");

//api documentation says you can post clientid/secret in either body or header
postparams.Add("client_id", spotifyClientId);
postparams.Add("client_secret", spotifySecret);

//var authHeader = Convert.ToBase64String(Encoding.Default.GetBytes($"{spotifyClientId}:{spotifySecret}"));
//webClient.Headers.Add(HttpRequestHeader.Authorization, "Basic " + authHeader);

var tokenResponse = webClient.UploadValues("https://accounts.spotify.com/api/token", postparams);

var textResponse = Encoding.UTF8.GetString(tokenResponse);

return Json(textResponse);

所以我收到的是响应(注意访问令牌很短)

"\"access_token\":\"BQAOYJZnfS0LPEwwZ_06Be76mx59bpoPsVPD0uTvvrwvDtSNi9flgeZQK8kDPSRyTFdE70iBk5PtEAvqnIQ\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"scope\":\"\"}"` 

当我尝试使用此令牌调用API时,出现了上面显示的错误。

如果我手动获取令牌,则可以从前端进行API调用

Documentation

1 个答案:

答案 0 :(得分:0)

我发现邮递员在调用授权后有一个代码示例。 成功进行oauth验证后,转到右上角的代码并编码示例代码,安装restsharp并删除一些参数,以得到类似以下的结果。

        var client = new RestClient("https://accounts.spotify.com/api/token");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Authorization", "Basic ODAzNTkzMDMxNzIwNGViNzlhMf54f45f5454fNTJhMTg=");
        request.AddParameter("grant_type", "authorization_code");
        request.AddParameter("code", code);
        request.AddParameter("redirect_uri", "http://localhost:8000/");

        IRestResponse response = client.Execute(request);

        return Json(response.Content);