Skip to content

Saving User Location

Rachael Wright-Munn edited this page Nov 22, 2022 · 5 revisions

Saving User Location

One of the more common things required of an authentication system is the ability to send the user back where they came. OmniAuth will automatically keep track of the HTTP_REFERER when you begin the authentication process, and will provide it to you in the callback phase as the omniauth.origin key in the environment hash. To use this, you would simply modify your callback action to redirect to the origin if it is already set:

class SessionsController < ApplicationController
  def callback
    # do your authentication stuff here...
    redirect_to request.env['omniauth.origin'] || '/default'
  end
end

How convenient!

⚠️ Note that if you're doing auth from a 3rd party domain, latest browsers (2020) may limit the referrer information to only the domain, not the full URL. In other words, when omniauth reads the HTTP_REFERER header, it would only see https://othersite.com instead of https://othersite.com/abc. Refer to https://web.dev/referrer-best-practices/ for full description and possible workarounds. The origin parameter functionality described below is not affected.

You can also customize the return URL by providing the origin query parameter in your initial omniauth URL:

/auth/twitter?origin=%2Fusers%2Fshow%2F24

Then, in the callback, you'd read it using request.env['omniauth.origin'], too.

You can test this redirection in your specs by setting the omniauth.origin using before_callback_phase as demonstrated below.

OmniAuth.config.before_callback_phase do |env|
  env['omniauth.origin'] = '/users/show'
end

Clone this wiki locally