patkil
patkil

Reputation: 2089

Spotify Web API Bad Request Error "invalid_client" when refreshing token

I'm building an app in Rails using the Spotify web API. I built a method to refresh a user's token, but am receiving a 400 error. According the the Spotify Web API docs, the header of my request needs to be in the following format:

Authorization: Basic <base64 encoded client_id:client_secret>

Using Httparty gem, here's the POST method to refresh the access token:

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

Here's what "result" ends up being:

=> #<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"]}>

I can decode client_id_and_secret and it returns "foo:bar", so I'm at a loss as to why I'm receiving a 400 error. Any insight is much appreciated.

Upvotes: 3

Views: 4090

Answers (1)

patkil
patkil

Reputation: 2089

Found the issue... it was with the Base64 encoding in Ruby. Apparently (as shown in Strange \n in base64 encoded string in Ruby) using the Base64.encode64('') method adds an extra line within the code. Using Base64.strict_encode64('') solved the issue.

Updated code:

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

Upvotes: 14

Related Questions