Calling Uber API from Rails: {“error”: “invalid_cl

2019-07-24 13:21发布

问题:

Been at this for a day.

Using Rails to call the Uber API and failing to get an access token. Grabbing the authorization code works, but exchanging for an access token does not.

I've tried with and without the OAuth 2.0 gem and made sure all my keys were accurate. Tried on two separate Uber accounts, too. All combinations give the same error: {"error": "invalid_client"}.

I'll post the non-OAuth code below. params[:code] is the auth code returned from Uber.

uri = URI.parse('https://login.uber.com/oauth/v2/token')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true

headers = {
  # authentication content-type is not json
  # 'Content-Type'  => 'application/x-www-form-urlencoded',
  'Authorization' => 'Token ' + @server_token
}

request = Net::HTTP::Post.new(uri.path, headers)

request.set_form_data({
  'client_id'     => @client_id,
  'client_secret' => @client_secret,
  'grant_type'    => 'authorization_code',
  'code'          => params[:code]
})

response = https.request(request)

render :json => response.body

Thanks in advance for the help.

回答1:

  • If you get {"error": "invalid_client"} then this means you are sending an additional HTTP request header which is not required but is validated by the Uber OAuth provider server.
    Another possible reason could be that you misspelled the request parameter names. (not your case)

    Solution: You need to remove the Authorization header from your request and try again, i.e. don't send any HTTP request headers.

  • If you have multiple redirect URLs defined in the Uber Developers Dashboard and you are making an authentication request without one keep in mind that the first URL defined in the dashboard is used:

    If none is provided the default is the first redirect URI provided in the application's dashboard.

    and if that first URL doesn't match the URL you used in the authorize step of the OAuth flow you will get {"error": "access_denied"}

    However, I've noticed that this error is raised even if the first URL matches the URL sent with the authorize step, so I recommend you send the redirect_uri parameter at each step of the OAuth flow.

    Solution: You need to send the redirect_uri parameter in the request (the same that you used on the authorize step)

  • If the code inside params[:code] has already been used once or has become invalid you get {"error": "invalid_grant"}

    Solution: You need to redo the authorize (first) step in the OAuth flow to obtain a new code which you need to exchange for an access token.