Search code examples
rubyapiactiverecordomniauthruby-on-rails-5

Rails 5 API Omniauth use ActiveRecord Session Store


Currently we are implementing a Rails 5 API with Omniauth and DeviseTokenAuth.

The initial portion seems to work great, however when attempting to validate the token and do anything further we get a CookieOverflow error. We deduced this was due to us storing >4KB of info from the Omniauth login.

We attempted to pivot to database stored sessions but continue to get errors from Omniauth

NoSessionError: You must provide a session to use OmniAuth

We are using

gem 'activerecord-session_store'

Our database migration is as follows

class AddSessionsTable < ActiveRecord::Migration
  def change
    create_table :sessions do |t|
      t.string :session_id, :null => false
      t.text :data
      t.timestamps
    end

    add_index :sessions, :session_id, :unique => true
    add_index :sessions, :updated_at
  end
end

Lastly we did set up on the config/application.rb the session store

config.session_store :active_record_store, :key => '_my_app_session'

I'm not sure whyw e continue to get the error of you must provide a session to use OmniAuth. If we switch this back to a cookiestore

config.middleware.use ActionDispatch::Flash
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore

The app recognizes the session but throws the CookieOverflow error.


Solution

  • You need to set config.api_only=false în your application.rb file. The middleware for session store is only added If this is Set to false .

    Adding the middleware manually doesn't work because the middleware is not instantiated în this case properly.

    You can check the code from Rails here : https://github.com/rails/rails/blob/92703a9ea5d8b96f30e0b706b801c9185ef14f0e/railties/lib/rails/application/default_middleware_stack.rb#L58