2017-02-28 132 views
1

我需要從Spotify Web API獲取訪問令牌。基於this documentation我寫了下面方法:Spotify Web API:基本授權

def authorize 
    grant = Base64.encode64("#{SPOTIFY_KEY}:#{SPOTIFY_SECRET}") 
    RestClient::Request.execute(
    method: :post, 
    url: 'https://accounts.spotify.com/api/token', 
    params: {'grant_type' => 'client_credentials'}, 
    headers: {"Authorization" => "BasiC#{grant}","Accept" => "*/*; q=0.5, application/json"} 
) 
end 

和以下RSpec的測試:

it 'authorize' do 
    obj = SpotifyIntegration.new 
    response = obj.authorize 
    myjson = JSON.parse(response.body) 
    expect(myjson.has_key?('access_token')).to be(true) 
    expect(myjson.has_key?('token_type')).to be(true) 
    expect(myjson['token_type']).to eq('bearer') 
    expect(myjson.has_key?('expires_in')).to be(true) 
end 

它發生的是,當我運行該測試中,生成該請求(補時RESTCLIENT_LOG = STDOUT)

RestClient.post 「https://accounts.spotify.com/api/token」, 「接受」=> 「/; q = 0.5,應用/ JSON」, 「接受編碼」=> 「的gzip,放氣」,「A uthorization 「=>」 基本Y2NmNTI3ODVlZWI1NDVlODk0ZmM2ZTY3YTZhNDM0ZDA6YTQ5MjdlOGFmOWQy \ nNGE0OTgyZDRkODI1MmJhZjBkNTI = \ n」

我得到

=> 400錯誤請求|應用程序/ json 131字節

而且它似乎確實是一個不好的請求,因爲我看不到grant_type => client_credentials的跡象。文檔說這是作爲請求主體參數的mandadory

我相信我發送這個錯誤的方式,但我不知道如何正確。

我試圖用RestClient#post代替RestClient::Request#execute,這樣做:

def authorize 
    grant = Base64.encode64("#{SPOTIFY_KEY}:#{SPOTIFY_SECRET}") 
    RestClient.post 'https://accounts.spotify.com/api/token', {'grant_type' => 'client_credentials'}.to_json, {"Authentication" => "BasiC#{grant}",content_type: :json, accept: :json} 
end 

,但後來我:

RESTClient實現:: UnsupportedMediaType: 415不支持的媒體類型

我如何使用RestClient寶石發送請求身體參數?

+0

當然可以。我做到了。用'{'grant_type'=>'client_credentials'}'我得到一個'400 Bad Request'。如果我使用'{'grant_type'=>'client_credentials'}。to_json'來完成,我在一些參考文獻中找到了'415 Unsupported Media Type' ... –

+0

同意,@Anthony。這就是爲什麼我驚訝它不起作用。真的不知道該怎麼做。 –

回答

2

問題是Base64編碼字符串的方式,該字符串包含大多數OAuth2提供程序不接受的換行符。你可以這樣做,而不是:

grant = Base64.encode64("#{client_id}:#{client_secret}").delete("\n") 

resp = RestClient.post('https://accounts.spotify.com/api/token', 
         {'grant_type' => 'client_credentials'}, 
         {"Authorization" => "BasiC#{grant}"}) 

this答案,新線每60個字符加(即新聞對我來說)。您可以使用另一種不包含換行符的方法,如strict_encode ...

grant = Base64.strict_encode64("#{client_id}:#{client_secret}") 
+0

它工作!非常感謝! –

1

這不完全是你要找的答案,但你應該明確地看看這個Ruby庫:rspotify。 Spotify Oauthentication很容易處理它。

+0

我知道。但我的項目需要我建立這個,我不能使用外部寶石。但謝謝你的建議! –