Invalid authorization code- Rails

Hello,

I’m currently building a Rails application with this Twitch gem. When I attempt to log in, I am correctly redirected to Twitch and back to my redirect URI, but attempting to get an access token with the provided auth code always fails.

Here’s the code on my redirect_uri (identical to the example provided in the gem’s README):

@twitch = Twitch.new({
  :client_id => CLIENT_ID,
  :secret_key => SECRET_KEY,
  :redirect_uri => REDIRECT_URI
})

@data = @twitch.auth(params[:code])
session[:access_token] = @data[:body]["access_token"]

As a quick side note, here are the relevant lines from the twitch gem:

def initialize(options = {})
	@client_id = options[:client_id] || nil
	@secret_key = options[:secret_key] || nil
	@redirect_uri = options[:redirect_uri] || nil
	@scope = options[:scope] || nil
	@access_token = options[:access_token] || nil

	@base_url = "https://api.twitch.tv/kraken"
end

def auth(code)
	path = "/oauth2/token"
	url = @base_url + path
	post(url, {
		:client_id => @client_id,
		:client_secret => @secret_key,
		:grant_type => "authorization_code",
		:redirect_uri => @redirect_uri,
		:code => code
	})
end

The parameters passed to my redirect_uri (auth code has been modified for privacy):

{"code"=>"rfyyvhb4jvcbd3t6wrcn12v24ybnzl6", "scope"=>"user_read"}

The API always responds with:

{:body=>{"error"=>"Bad Request", "status"=>400, "message"=>"Invalid authorization code"}, :response=>400}

Thanks!

Did a quick check of the POST request for the token by sending it to RequestBin- all parameters appear correct.

At this point I’m pretty lost- as far as I can tell, I’m sending a properly formatted POST request to https://api.twitch.tv/kraken/oauth2/token. The API says that the auth code is wrong, but inspecting the request I send, the code is exactly identical to the one I receive immediately beforehand. Any tips on what might be the issue here?

Hmm, the only reason you should get that error (assuming the login flow is all correct) is due to trying to re-use an auth token. What is your client_id, and what user were you trying to login with?

client_id: flz2nj3mgm3ln8w7h40bexemyug33d8
Logging in with Twitch user isspkmn

Thanks for the help!

From our logs it seems like you are requesting the token twice. The first time succeeds, the second time fails as we invalidate the auth code after it’s first use.

Found the bug on my end- the gem was making two POST calls. Thanks again, Fugiman.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.