2014-08-31 144 views
1

我正在使用Spotify Web API在Rails中构建应用程序。我构建了一个刷新用户令牌的方法,但收到400错误。根据Spotify的网络API文档,我的请求的头必须采用以下格式:刷新令牌时Spotify Web API错误请求错误“invalid_client”

Authorization: Basic <base64 encoded client_id:client_secret> 

使用Httparty宝石,这里的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并返回“富:酒吧”,所以我很茫然,为什么我收到一个400错误。任何见解都非常感谢。

回答

10

发现这个问题......它与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 
相关问题