ruby-on-rails - 刷新 token 时 Spotify Web API 错误请求错误 "invalid_client"

标签 ruby-on-rails spotify httparty

我正在使用 Spotify Web API 在 Rails 中构建应用程序。我构建了一个方法来刷新用户的 token ,但收到 400 错误。根据 Spotify Web API 文档,我的请求的 header 需要采用以下格式:

Authorization: Basic <base64 encoded client_id:client_secret>

使用 Httparty gem,这里是刷新访问 token 的 POST 方法:
def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
    "https://accounts.spotify.com/api/token",
    :body => {:grant_type => "refresh_token",
              :refresh_token => "#{self.oauth_refresh_token}"},
    :headers => {"Authorization" => "Basic #{client_id_and_secret}"}
    )
end

这就是“结果”最终的结果:
=> #<HTTParty::Response:0x7f92190b2978 parsed_response={"error"=>"invalid_client", "error_description"=>"Invalid client secret"}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>["Sun, 31 Aug 2014 22:28:38 GMT"], "content-type"=>["application/json"], "content-length"=>["70"], "connection"=>["close"]}>

我可以解码 client_id_and_secret 并返回“foo:bar”,所以我不知道为什么我会收到 400 错误。任何见解都非常感谢。

最佳答案

发现问题...它与 Ruby 中的 Base64 编码有关。显然(如 Strange \n in base64 encoded string in Ruby 所示)使用 Base64.encode64('') 方法在代码中添加了额外的一行。使用 Base64.strict_encode64('') 解决了这个问题。

更新代码:

def refresh_token
client_id = "foo"
client_secret = "bar"
client_id_and_secret = Base64.strict_encode64("#{client_id}:#{client_secret}")
result = HTTParty.post(
    "https://accounts.spotify.com/api/token",
    :body => {:grant_type => "refresh_token",
              :refresh_token => "#{self.oauth_refresh_token}"},
    :headers => {"Authorization" => "Basic #{client_id_and_secret}"}
    )
end

关于ruby-on-rails - 刷新 token 时 Spotify Web API 错误请求错误 "invalid_client",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25596936/

相关文章:

Spotify 应用程序/主目录位置(Windows 本地开发)?

ruby-on-rails - HTTParty针对Rails的内容类型问题

ruby-on-rails - 向雪球添加省略过滤器

ruby-on-rails - 从 Rails 表单生成器获取数据属性值,而不使用输入字段

desktop-application - 使用什么语言或技术来开发 Spotify 桌面应用程序?

android - 使用 Android Intent 启动 Spotify Radio

ruby-on-rails - Rails + HTTParty : Expecting JSON data in the body

ruby-on-rails - 使用 HTTParty 解析 HTTP header 'set-cookie'

ruby-on-rails - 将文件上传为字符串(Ruby on rails)

ruby-on-rails - 在 Ruby on Rails 3 上上传多个文件