2014-08-31 132 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 
相關問題