sffc
sffc

Reputation: 6424

Session variable not initialized on callback from OmniAuth OpenID

I need to allow users of my application to associate an OpenID with their account after they are already logged in.

In the last controller visited before I defer to OmniAuth, I set the user ID to the session. The relevant code is:

class UsersController < ApplicationController
  def confirm
    session[:user_id] = @user.id
  end
end

The user then links to /auth/openid. This works as expected. Here is the OmniAuth initializer:

require 'openid/store/filesystem'
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :open_id, :store => OpenID::Store::Filesystem.new('/tmp'), :name => 'openid'
end

When the user comes back from OpenID, I route them to the sessions controller, like this (in routes.rb):

match 'auth/:provider/callback', to: 'sessions#process_omniauth'

Here is the relevant code from sessions_controller.rb:

class SessionsController < ApplicationController
  def process_omniauth
    auth_hash = request.env['omniauth.auth']
    puts "SESSION: #{session}"
    # ...
  end
end

The strange thing is, the session variable does not seem to be initialized with the user_id from the previous controller.

If I go to some other page in my application, the user_id is in session as expected.

If I try assigning the OmniAuth hash to the session variable, however, it erases whatever session was there before. For example, if I run session[:omniauth] = auth_hash in the process_omniauth block above, this information is available in the session to other parts of my application, but the user_id seems to have been forgotten if I do this!

Any ideas?

Upvotes: 2

Views: 981

Answers (1)

Brian Morearty
Brian Morearty

Reputation: 3348

I had the same problem. What found was that when OmniAuth calls me back, session and request.env['rack.session'] were both empty but request.env['action_dispatch.request.unsigned_session_cookie'] has all the session keys.

I have not figured out why the discrepancy.

Eventually I found the answer here:

OmniAuth - current session not loaded on OpenID callback.

Upvotes: 2

Related Questions