Ruby On Rails: Session Handling

View on Github

Ruby On Rails: Session Handling

Gravatar for andres.aguiar@auth0.com
By Andres Aguiar
Auth0

Learn how to store user data in your session and clean it up upon logout. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to integrate with my app

15 minutes
  1. Store Session Data on Login
  2. Clear Session on Logout
Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: Ruby 2.3.1+ | Rails 5.0.0+ or Rails 4.2.0+

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'
end

Clear Session on Logout

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
    reset_session
    redirect_to logout_url.to_s
  end
end

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
    }

    URI::HTTPS.build(host: domain, path: '/v2/logout', query: to_query(request_params))
  end

  private

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

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

Use Auth0 for FREE