Why your omniauth just broke in Rails.

TL:DR;omniauth-oauth2 introduced a breaking change in 1.4.0 for some strategies, causing an invalid URI error. The easiest way to fix it is to revert to 1.3.1 in your Gemfile.


Last night, while building a prototype in Rails that uses OAuth2 for user authentication with the Spotify API, I kept getting errors that looked like this in the server output:

invalid_grand: Invalid redirect URI {"error”:"invalid_grant","error_description":"Invalid redirect URI"}

This was a head scratcher, because I had built the user sessions controller myself. At first I thought it was an error in the callback URIs that I had provided to Spotify, so I double checked those:

No problems there. My router file has a route for an auth_out that directs to

'auth/:provider/’

and a callback route to

'auth/:provider/callback', to: 'sessions#create',

and my sessions controller had a create method, so there was no reason this shouldn’t work.

A few steps in the middle to check that my ENV['SPOTIFY_ID'] and ENV[SPOTIFY_SECRET] were correct, check that my omniauth.rb initializer was correct, and I decided that there must be another reason. I searched the error code and came across a few Stack Overflow posts that mentioned it but none had good answers, so I decided to dig into the omniauth-oauth2 source code to see if that was the reason. Bingo.

It turns out there was a backwards-incompatible update to the gem that injects the code and state parameters into the callback URI. This means that when Spotify authenticates the user and attempts to send a request to the callback URI, it won’t match the provided URIs (which don’t have those params) and will cause an error. How do I fix this?

There are several ways to fix it, including building a custom strategy (lots more work) or hardcoding the URI (probably better in the long term), but the easiest way to fix it is just to back-date the gem.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.