2017-09-02 252 views
1

我試圖讓我的應用程序通過他們的Authorization Code Flow登錄Spotify。我能設法得到一個訪問令牌時從Spotify的接收授權code在初始授權步驟,但收到以下錯誤:Spotify授權代碼

{"error":"invalid_client","error_description":"Invalid client"}

我的代碼如下:

# Callback from Spotify Authorization 
get '/auth/spotify/callback' do 
    session[:code] = params[:code] 
    redirect to '/refresh' 
end 

然後,我張貼如下:

get '/refresh' do 
    uri = URI('https://accounts.spotify.com/api/token') 
    resp = Net::HTTP.post(uri, 
    { 
     "grant_type" => "authorization_code", 
     "code" => session[:code].to_s, 
     "redirect_uri" => "http://localhost:4567/auth/spotify/callback", 
     "client_id" => client_id, 
     "client_secret" => client_secret 
    }.to_json 
) 
    "#{resp.body}" 
end 

任何幫助,將不勝感激

編輯:我也試過使用PostMan POST上述相同的參數,但收到相同的錯誤消息

+0

這看起來像一個非常典型的OAuth2流程的正確方法。爲了簡單起見,您可能需要考慮使用[oauth2](https://github.com/intridea/oauth2)之類的內容。 – coreyward

回答

1

您需要在您的POST請求中添加授權標頭。

添加以下關鍵在你的Net :: HTTP.post選項:

{'Authorization' => 'Basic YOUR_AUTH_CODE' }

編輯:

這是'Your application requests refresh and access tokens'標題下的文檔。

+0

是的,我見過這個。但是'Authorzation'部分下方還有一段代碼,說你可以在你的body中包含你的非base64編碼id和祕密。無論如何,我試過你的方式,仍然收到相同的錯誤 – Andy

+0

你仍然可以嘗試添加授權標題並刪除client_id,secret_id鍵嗎? – MaieonBrix

+0

如果我添加一個頭文件,錯誤信息變爲'{「error」:「unsupported_grant_type」,「error_description」:「grant_type必須是client_credentials,authorization_code或refresh_token」} SEE:https://gist.github.com/ mindovermiles262/66ff2fc1da8c4c6220365f16845ca8ae – Andy

1

要回答我的問題:

我並不需要做,因爲我用,'omniauth-spotify'創業板的要求,可以在request.env['omniauth.auth'].credentials.token

我也創建訪問令牌還給我POST請求不正確。下面的例子是使一個POST,將獲得從refresh_token新令牌(在上述.credentials散列提供)

# Get new access token from refresh token 
# session[:creds] = request.env['omniauth.auth'].credentials 

get '/refresh' do 
    refresh_token = session[:creds].refresh_token 
    auth = "Basic " + Base64.strict_encode64("#{client_id}:#{client_secret}") 
    uri = URI.parse('https://accounts.spotify.com/api/token') 
    request = Net::HTTP::Post.new(uri) 
    request["Authorization"] = auth 
    request.set_form_data(
    "grant_type" => "refresh_token", 
    "refresh_token" => refresh_token, 
) 

    req_options = { 
    use_ssl: uri.scheme == "https", 
    } 

    response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| 
    http.request(request) 
    end 

    "#{response.code}" # > 200 OK 

end