繁体   English   中英

Spotify oauth 在尝试获取 access_token 时返回 400

[英]Spotify oauth is returning a 400 when trying to get access_token

我正在尝试从 spotify api 获取 access_token。 发现文档

但是我总是收到响应 400, {"error"=>"invalid_grant", "error_description"=>"Invalid authorization code"}

我正在运行的代码最初是,authorization_code 来自 controller,它是params[:code]中返回的内容

    response = HTTParty.post(
      'https://accounts.spotify.com/api/token',
      body: {
         grant_type: 'authorization_code',
         code: authorization_code,
         redirect_uri: redirect_uri
        }
      ),
      headers: {
        'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
      }
    )

我阅读了有关表单编码的信息,所以我尝试了

    response = HTTParty.post(
      'https://accounts.spotify.com/api/token',
      body: URI.encode_www_form(
        {
         grant_type: 'authorization_code',
         code: authorization_code,
         redirect_uri: redirect_uri
        }
      ),
      headers: {
        'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    )

但这无济于事......我已经尝试了我能想到的每一种组合,但无法让它发挥作用。

redirect_uri 绝对正确,因为当我更改它提供 bad_uri 方法并且授权有效时,我可以使用Implicit Grant查询 api

如果有人有任何经验/解决方案,我将不胜感激

我认为你不需要自己编码身体。 设置 header 应该足够了。 您可能必须对redirect_uri进行 URL 编码,因为它必须与第一个/授权代码请求中使用的值匹配。

response = HTTParty.post('https://accounts.spotify.com/api/token',
  body: {
    grant_type: 'authorization_code',
    code: authorization_code,
    redirect_uri: redirect_uri
  },
  headers: {
    'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
    'Content-Type' => 'application/x-www-form-urlencoded'
  }
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM