Ruby On Rails: Session Handling

Gravatar for
By Andres Aguiar

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Ruby 2.3.1
  • Rails 5.0.0
Show requirements

Store Session Data on Login

Upon successful authentication, OmniAuth sets the authentication hash of a request to /auth/oauth2/callback. To handle this request, add a new route in your routes file.

get "/auth/oauth2/callback" => "auth0#callback"

Store the user information in the session in auth0_controller/callback.

# app/controllers/auth0_controller.rb

def callback
  # This stores all the user information that came from Auth0
  # and the IdP
  session[:userinfo] = request.env['omniauth.auth']

  # Redirect to the URL you want after successful auth
  redirect_to '/dashboard'

Logout Action

Use the following command to create the controller that will handle user logout:

rails generate controller logout

To clear out all the objects stored within the session, call the reset_session method within the logout_controller/logout method. Learn more about reset_session here.

# app/controllers/logout_controller.rb

class LogoutController < ApplicationController
  include LogoutHelper
  def logout
    redirect_to logout_url.to_s

In logout_helper.rb file add the methods to generate the logout URL.

# app/helpers/logout_helper.rb

module LogoutHelper
  def logout_url
    domain = Rails.application.secrets.auth0_domain
    client_id = Rails.application.secrets.auth0_client_id
    request_params = {
      returnTo: root_url,
      client_id: client_id
    } domain, path: '/v2/logout', query: to_query(request_params))


  def to_query(hash) { |k, v| "#{k}=#{URI.escape(v)}" unless v.nil? }.reject(&:nil?).join('&')

The final destination URL (the returnTo value) needs to be in the list of Allowed Logout URLs. See the logout documentation for more.

Previous Tutorial
1. Login
Next Tutorial
3. User Profile
Was this article helpful?
Use Auth0 for FREECreate free Account