简体   繁体   中英

Spotify oauth is returning a 400 when trying to get access_token

I am trying to get an access_token from the spotify api. spotify docs

However i am always getting a response 400, {"error"=>"invalid_grant", "error_description"=>"Invalid authorization code"}

The code i am running was originally, the authorization_code is the from the controller and it is what is returned in the 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}"),
      }
    )

I read about form encoding so i tried

    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'
      }
    )

but this has been to no avail... i have tried what i can think of as every combination and cannot get it to work.

The redirect_uri is definitely right as when i change that it gives a bad_uri method and the authorization works as i can query the api with Implicit Grant

If anyone has any experience/solutions i would be much obliged

I think you don't need to encode the body on your own. Setting the header should be enough. You may have to URL encode the redirect_uri , as it must match with the value used in the first/authorization code request.

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'
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM