簡體   English   中英

Spotify oauth 在嘗試獲取 access_token 時返回 400

[英]Spotify oauth is returning a 400 when trying to get access_token

我正在嘗試從 spotify api 獲取 access_token。 發現文檔

但是我總是收到響應 400, {"error"=>"invalid_grant", "error_description"=>"Invalid authorization code"}

我正在運行的代碼最初是,authorization_code 來自 controller,它是params[:code]中返回的內容

    response = HTTParty.post(
      'https://accounts.spotify.com/api/token',
      body: {
         grant_type: 'authorization_code',
         code: authorization_code,
         redirect_uri: redirect_uri
        }
      ),
      headers: {
        'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
      }
    )

我閱讀了有關表單編碼的信息,所以我嘗試了

    response = HTTParty.post(
      'https://accounts.spotify.com/api/token',
      body: URI.encode_www_form(
        {
         grant_type: 'authorization_code',
         code: authorization_code,
         redirect_uri: redirect_uri
        }
      ),
      headers: {
        'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
        'Content-Type' => 'application/x-www-form-urlencoded'
      }
    )

但這無濟於事......我已經嘗試了我能想到的每一種組合,但無法讓它發揮作用。

redirect_uri 絕對正確,因為當我更改它提供 bad_uri 方法並且授權有效時,我可以使用Implicit Grant查詢 api

如果有人有任何經驗/解決方案,我將不勝感激

我認為你不需要自己編碼身體。 設置 header 應該足夠了。 您可能必須對redirect_uri進行 URL 編碼,因為它必須與第一個/授權代碼請求中使用的值匹配。

response = HTTParty.post('https://accounts.spotify.com/api/token',
  body: {
    grant_type: 'authorization_code',
    code: authorization_code,
    redirect_uri: redirect_uri
  },
  headers: {
    'Authorization' => 'Basic ' + Base64.strict_encode64("#{client_id}:#{client_secret}"),
    'Content-Type' => 'application/x-www-form-urlencoded'
  }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM