Ruby On Rails: Session Handling

View on Github

Ruby On Rails: Session Handling

Gravatar for
By Josh Cunningham

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

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out 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/auth0/callback. To handle this request, add a new route in your routes file.

get "/auth/auth0/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'

Clear Session on 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
Use Auth0 for FREE