Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple Authentication in Rail 4 Using Bcrypt

#Simple Authentication with Bcrypt

This tutorial is for adding authentication to a vanilla Ruby on Rails app using Bcrypt and has_secure_password.

The steps below are based on Ryan Bates's approach from Railscast #250 Authentication from Scratch (revised).

You can see the final source code here: repo. I began with a stock rails app using rails new gif_vault


  1. Create a user model with a name, email and password_digest (all strings) by entering the following command into the command line: rails generate model user name email password_digest.

    Note: If you already have a user model or you're going to use a different model for authentication, that model must have an attribute names password_digest and some kind of attribute to identify the user (like an email or a username).

  2. Run rake db:migrate in the command line to migrate the database.

  3. Add these routes below to your routes.rb file. Notice I also deleted all the comments inside that file. Don't forget to leave the trailing end, though.

    # config/routes.rb
    GifVault::Application.routes.draw do
        # This route sends requests to our naked url to the *cool* action in the *gif* controller.
        root to: 'gif#cool'
        # I've created a gif controller so I have a page I can secure later. 
        # This is optional (as is the root to: above).
        get '/cool' => 'gif#cool'
        get '/sweet' => 'gif#sweet'
        # These routes will be for signup. The first renders a form in the browse, the second will 
        # receive the form and create a user in our database using the data given to us by the user.
        get '/signup' => 'users#new'
        post '/users' => 'users#create'
  4. Create a users controller:

    # app/controllers/users_controller.rb
    class UsersController < ApplicationController
  5. Add a new action (for rendering the signup form) and a create action (for receiving the form and creating a user with the form's parameters.):

    # app/controllers/users_controller.rb
    class UsersController < ApplicationController
        def new
        def create
  6. Now create the view file where we put the signup form.

    <!-- app/views/users/new.html.erb -->
    <%= form_for :user, url: '/users' do |f| %>
      Name: <%= f.text_field :name %>
      Email: <%= f.text_field :email %>
      Password: <%= f.password_field :password %>
      Password Confirmation: <%= f.password_field :password_confirmation %>
      <%= f.submit "Submit" %>
    <% end %>

    A note on Rail's conventions: This view file is for the new action of the users controller. As a result, we save the file here: /app/views/users/new.html.erb. The file is called new.html.erb and it is saved inside the views folder, in a folder we created called users.

    That's the convention: view files are inside a folder with the same name as the controller and are named for the action they render.

  7. Add logic to create action and add the private user_params method to sanitize the input from the form (this is a new Rails 4 thing and it's required). You might need to adjust the parameters inside the .permit() method based on how you setup your User model.

class UsersController < ApplicationController

def new

def create
  user =
    session[:user_id] =
    redirect_to '/'
    redirect_to '/signup'


def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation)

end ```

  1. Go to your Gemfile and uncomment the 'bcrypt' gem. We need bcrypt to securely store passwords in our database.

    source ''
    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
    gem 'rails', '4.0.4'
    # Use sqlite3 as the database for Active Record
    gem 'sqlite3'
    # Use ActiveModel has_secure_password
    gem 'bcrypt', '~> 3.1.7'
  2. Go to the User model file and add has_secure_password. This is the line of code that gives our User model authentication methods via bcrypt.

    # app/models/user.rb
    class User < ActiveRecord::Base
  3. Run bundle install from the terminal then restart your rails server.

    Note: Windows users might have issues with bcrypt. If so, copy the error into Google and look for answers on Stack Overflow. There is documentation online for how to fix Windows so the bcrypt works.

  4. Create a sessions controller. This is where we create (aka login) and destroy (aka logout) sessions.

    # app/controllers/sessions_controller.rb
    class SessionsController < ApplicationController
      def new
      def create
      def destroy
  5. Create a form for user's to login with.

    <!-- app/views/sessions/new.html.erb -->
    <%= form_tag '/login' do %>
      Email: <%= text_field_tag :email %>
      Password: <%= password_field_tag :password %>
      <%= submit_tag "Submit" %>
    <% end %>
  6. Update your routes file to include new routes for the sessions controller.

    GifVault::Application.routes.draw do
      root to: 'gif#cool'
      # these routes are for showing users a login form, logging them in, and logging them out.
      get '/login' => 'sessions#new'
      post '/login' => 'sessions#create'
      get '/logout' => 'sessions#destroy'
      get '/signup' => 'users#new'
      post '/users' => 'users#create'
  7. Update the sessions_controller with the logic to log users in and out.

      # app/controllers/sessions_controller.rb
      def create
        user = User.find_by_email(params[:email])
        # If the user exists AND the password entered is correct.
        if user && user.authenticate(params[:password])
          # Save the user id inside the browser cookie. This is how we keep the user 
          # logged in when they navigate around our website.
          session[:user_id] =
          redirect_to '/'
        # If user's login doesn't work, send them back to the login form.
          redirect_to '/login'
      def destroy
        session[:user_id] = nil
        redirect_to '/login'
  8. Update the application controller with new methods to look up the user, if they're logged in, and save their user object to a variable called @current_user. The helper_method line below current_user allows us to use @current_user in our view files. Authorize is for sending someone to the login page if they aren't logged in - this is how we keep certain pages our site secure... user's have to login before seeing them.

    # app/controllers/application_controller.rb
    class ApplicationController < ActionController::Base
      # Prevent CSRF attacks by raising an exception.
      # For APIs, you may want to use :null_session instead.
      protect_from_forgery with: :exception
      def current_user
        @current_user ||= User.find(session[:user_id]) if session[:user_id]
      helper_method :current_user
      def authorize
        redirect_to '/login' unless current_user
  9. Add a before_filter to any controller that you want to secure. This will force user's to login before they can see the actions in this controller. I've created a gif controller below which I'm going to secure. The routes for this controller were added to the routes.rb in the beginning of this tutorial.

    # app/controllers/gif_controller.rb
    class GifController < ApplicationController
      before_filter :authorize
      def cool
      def free
  10. You can update your application layout file to show the user's name if they're logged in and some contextual links.

    <!-- app/views/layout/application.html.erb -->
    <!DOCTYPE html>
      <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
      <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
      <%= csrf_meta_tags %>
    # added these lines.
    <% if current_user %>
      Signed in as <%= %> | <%= link_to "Logout", '/logout' %>
    <% else %>
      <%= link_to 'Login', '/login' %> | <%= link_to 'Signup', '/signup' %>
    <% end %>
    <%= yield %>

##Things Missing

  • Adding flash messages would be simple and provide feedback to the user if things go wrong.

-- All done! Feel free to fork and update this. Reach me at @thebucknerlife on Twitter.

Copy link

jamesaduke commented Aug 10, 2016

really great tutorial

Copy link

martinbeentjes commented Aug 23, 2016

Great straight-to-the-point tutorial! Thanks for this!

Copy link

cloudsben commented Sep 7, 2016

Great Tutorial !

Copy link

aaossa commented Sep 20, 2016

If you're on Windows, using Ruby 2.3 and bcrypt gives you problems, this comment was the solution for me 👌

Copy link

levanlinh1995 commented Oct 2, 2016

tks, nice

Copy link

i8igmac commented Nov 6, 2016

this is frustrating... everything looks good but it dont work...

after creating a user account, i expect to see a new page like '/home'

welcome to a new page, you are logged in

Copy link

ziomio commented Dec 13, 2016

awesome, thank you!

Copy link

RayedB commented Dec 20, 2016

This tutorial is the real deal! Thanks !

Copy link

samguergen commented Dec 29, 2016

You are the man. Thank you!

Copy link

9mm commented Jan 17, 2017

You should use session.delete(:user_id) instead.

session[:user_id] = nil will leave the :user_id key in the session hash, this will destroy the key and value, as if your session never had any value assigned to that key.

Copy link

ancaciascaiu commented Feb 17, 2017

Hi, I find this guide really useful, but I discovered a mistake that can trigger misunderstanding: The Note in Part 1 says "that model must have an attribute names password_digest". The correct way to say this is that you need to leave the model attribute as "password" and make sure you have a migration attribute of "password_digest". This way it'll work. :)

Copy link

MauricioRibeiroA commented Mar 21, 2017

Perfect explanation!

Copy link

export-mike commented Apr 3, 2017

you might want to reconsider your session ids to be unique for a given session and not the user id.

Copy link

caronalex06 commented May 19, 2017

Perfect and simple. Wow ! Thanks.

Copy link

ip-ilamparithi commented Aug 8, 2017

how to set a persistent cookie using bcrypt?

Copy link

vamuigua commented Aug 9, 2017

Thanks...Bcrypt is cool!

Copy link

BertZZ commented Sep 16, 2017

Does this still all work on rails 5

Copy link

jattoabdul commented Nov 29, 2017

thanks alot for this man

Copy link

ajcubeta commented Dec 20, 2017

Thanks man, this really helps. Moving Devise to BCrypt =)

Copy link

lreb commented Jan 23, 2018

thank you

Copy link

stevecondylios commented Feb 17, 2018

It works on rails 5, just change




Copy link

triton11 commented Mar 9, 2018

Just wanted you to know its 2018 and this guide is still so helpful!

Copy link

dhoangk07 commented May 7, 2018

Thanks for posting, this one is very helpful.

Copy link

reemhosny commented Jun 30, 2018

it also works on rails 5
Thanks a lot , great work

Copy link

stevecondylios commented Jul 13, 2018

I experienced a bug where a user couldn't immediately sign back in after signing out. This seemed to fix it:

In application.html.erb, replace
<%= link_to "Logout", '/logout' %>

<%= link_to "Logout", '/logout', data: { turbolinks: false } %>

Copy link

foundsatis commented Jan 6, 2019

Still helpful in 2019!

Thanks for the guide. Exactly what I wanted.


Using before_filter :authorize, didn't work for me. I used before_action :authorize instead.

Copy link

xiaocuixt commented Mar 11, 2019

Simply, before_filter is for rails3 and before, before_action is for rails4 and later.

Copy link

roman-on commented Jan 7, 2022

Wow..thank you so much.. one of the best explanations and plus it's working perfect and smooth! Great job... no words to add.

Copy link

chingsley commented Jan 23, 2022

this is a nice piece, thanks!

Copy link

ekeneezeani commented Oct 20, 2022

This is just too good and still helpful in 2022. Thanks a million!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment