Introduction User accounts are an indispensable feature of web applications. They allow us to create persistent, tailored experiences for the people using our site. They also help us better track how our application is used. Despite their usefulness, implementing user accounts can be akin to opening Pandora’s box of troubles. We live in an age of savvy sackers of digital domains. While we’ve opened a box of possibilities, they’ve brought a host of problems with them! How do we stand a chance? We lean on others’ work and trade configuration for convention. But before we find some shoulders to stand on, let’s get a sense of the problem we’re trying to solve. Signing Up And Signing In and are actions with which we are all familiar. They allow web applications to and their users. Signing Up Signing In authenticate authorize When we , we create a means by which a web application determines that we are who we say we are. Signing Up happens once in the lifetime of a user in an application. It creates a new user instance in the backend of the server with information that can be use to that user. Authentication asks the question, “Are you who you say you are?” When we sign in, we are authenticated by the application based on the username and password we provide, and consequently given access to different features of the application. Sign Up authenticate We are engaged in when we only have to provide one type of information to authenticate ourselves. As you might imagine, single-factor authentication is not the best means of securing user accounts, as anyone with a username and password can access an account. single-factor authentication That’s where authentication comes into play. We encounter multi-factor authentication pretty well every day, when a site asks us to enter a randomly generated code sent to our phones in addition to our username and password, or when an ATM machine requires us to enter a PIN number and insert our debit card. We won’t build multi-factor authentication in this post, but it’s important to be aware of. multi-factor Once we’re signed in and authenticated by an application, it will check to see if we are to perform the actions we attempt to perform. Authorization asks the question, “Are you allowed to do that?” The means by which a web application authorizes a user is through cookies, specifically, session cookies. authorized A cookie is a bit of data stored on a user’s browser. Web applications can store all kinds of information in cookies to track a user’s state and history. A session cookie is a cookie that lasts for the duration of a session on a web application, typically from sign/log in to sign/log out. When a user signs in, the user’s browser is given a cookie by the web application identifying that user. The authorization of the user can then be checked when HTTP requests are made of the application. Signing up happens once in the lifetime of user on a web application. It gives the application a means of authenticating the user, or checking to see that they are who they say they are, through a username, password, and any other required information. When a user signs in, they are authenticated and given an identifying session cookie. As the user interacts with the application, the application can check to see that the user is authorized, or permitted, to perform an action by referencing the user’s cookie. Authentication with bcrypt Authentication is a web application’s way of checking to see that a user is who they say they are. There are several Ruby gems already written to facilitate this process. is one of the most popular, along with and . devise omniauth doorkeeper We’re not going to use any of those! For the purposes of understanding the process of authentication and authorization, we’ll be using a gem that’s been staring you in the face since you first opened a Rails Gemfile: . bcrypt Uncomment that guy! source git_source( ) { } ... gem , ... 'https://rubygems.org' :github |repo| "https://github.com/ .git" #{repo} # ruby '2.5.1' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 4.0' # Use ActiveModel has_secure_password 'bcrypt' '~> 3.1.7' # Use ActiveStorage variant # gem 'mini_magick', '~> 4.8' the Ruby gem is based on bcrypt the OpenBSD hashing algorithm. Given any string, such as a password, the hash will scramble the string along with a dash of random characters (known as salt) in such a way that the process cannot be reversed or guessed. bcrypt the Ruby gem allows us to use the bcrypt algorithm to hash passwords, and it also manages storing the salt used in hashing so that we can later authenticate our users. bcrypt pw = BCrypt::Password.create( ) pw == 'P4ssW02d!' # => "$2a$12$YNW0EG8VwLmy1l9yxMeyAOaen/Yhx7LTBJR6G7jnG2WMkr9fo7aO6" 'P4ssW02d!' # => true bcrypt and the User Model In order to use , our user table must have a attribute. In your Rails projects, you might execute the following: . bcrypt password_digest rails generate resource User username password_digest After migrating the table, we should have a schema similar to the following: create_table , t.string t.string t.datetime , t.datetime , "users" force: :cascade do |t| "username" "password_digest" "created_at" null: false "updated_at" null: false end Note that we’re storing a password digest, not a password. Never, ever, for any reason, whatsoever, even if your mother asks you too, even if you think it will cure your foot fungus, never store passwords in plain text. We must also add to our User model. You'll notice that I've added some validations to ensure our users are created with a unique username and non-unique password. require unique passwords, as it will give ne'er-do-wells the information and confidence they need to gain access to user accounts. has_secure_password Do not has_secure_password validates , , validates , < ApplicationRecord class User :username presence: true uniqueness: true :password presence: true end is a helper method for models that gives them access to methods which will aid in authentication. We can test them in . has_secure_password rails console usr = User.create( , , ) usr.authenticate( ) usr.authenticate( ) username: "cheetochester" password: "Ch33zy$" password_confirmation: "Ch33zy$" # => #<User id: 4, username: "cheetochester", password_digest: "$2a$12$Io.kXzHPXoGZYzuWBawSFOawjvGNmsrHsCiXbNhlYep..." ...> "cheesys" # => false "Ch33zy$" # => #<User id: 4, username: "cheetochester", password_digest: "$2a$12$Io.kXzHPXoGZYzuWBawSFOawjvGNmsrHsCiXbNhlYep..." ...> Note that when we create a new user, we do so with the and keys, not . password password_confirmation password_digest handles validating password and and converting password into the that is saved in the database. Given a password string, the method returns false if the password is incorrect, and the user instance if the password is correct. bcrypt password_confirmation password_digest #authenticate Routes Before we can confidently set up our controllers, we must have a clear vision of our routes. In this basic example application, users can create and view their accounts. They can also sign in and out of their accounts. We will manage this functionality with the following routes in : rails-app/config/routes.rb Rails.application.routes.draw resources , [ , ] get , get , post , delete , do :users only: :create :show "/signup" to: "users#new" "/login" to: "sessions#new" "/sessions" to: "sessions#create" "/sessions" to: "sessions#destroy" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end Creating a Sign Up Form The code excerpt below depicts a basic User controller. We have supported actions for creating a user and seeing their page. @user = User.new @user = User.create(user_params) @user.valid? @user.save redirect_to @user redirect @user = User.find(params[ ]) private params. ( ).permit( , , ) < ApplicationController class UsersController def new end def create if else :new end end def show :id end def user_params require :user :username :password :password_confirmation end end There is no special sauce for creating a sign up form. We simply need a form that will pass , , and to our application. In we can generate a form with Rails form helpers like so: username password password_confirmation rails-app/app/views/users/new.html.erb <%= form_for @user %> <%= f.label %> <%= f.text_field , %> <%= f.label %> <%= f.password_field , %> <%= f.label %> <%= f.password_field , %> <%= f.submit %> <% %> do |f| :username :username placeholder: "Username" :password :password placeholder: "Password" :password_confirmation :password_confirmation placeholder: "Confirm Password" "Create Account" end On submission, our action will attempt to create a new user instance with those parameters. If the user instance is valid, the user will be redirected to their show page. Otherwise, the user will be redirected to the new user page. UsersController#create Logging In Logging in, or signing in, will be handled through Rails’ hash, which reads and manages a cookie on a user's browser. Managing session requires enough unique actions to warrant another controller. We'll call this controller the . session session SessionsController @user = User.find_by( params[ ]) @user && @user.authenticate(params[ ]) session[ ] = @user.id redirect_to @user redirect_to login_path < ApplicationController class SessionsController def new end def create username: :username if :password :user_id else end end end In this controller we’ve defined two actions. is simply responsible for rendering a page that enables a user to create a new session (also known as log in). SessionsController#new The contents of maybe as simple as: rails-app/app/views/sessions/new.html.erb <%= form_tag sessions_path %> <%= label_tag %> <%= text_field_tag , , %> <%= label_tag %> <%= password_field_tag , , %> <%= submit_tag %> <% %> do "Username" :username nil placeholder: "Username" "Password" :password nil placeholder: "Password" "Log In" end The purpose of this form is to prompt the authentication of a user and the storage of their identity in the cookie. session In , we first try to find the user based on their username. If the user exists, we authenticate them using the password provided in the form and the method granted to us by the gem. If they are authenticated, we will store their id in the session cookie ( ). SessionsController#create #authenticate bcrypt session[:user_id] = @user.id Otherwise, they will be redirected to the login path. What keeps someone from simply modifying their session cookie to mimic a user? Lucky for us, Rails encrypts the cookies that it creates! Laying the Foundation for Authorization with bcrypt We’ve implemented authentication with a couple of forms, a handful of routes and controller actions, and a few methods. And yet a one-winged bird can't fly. We need authorization to put our authentication to work. bcrypt We can lay the foundation for authorization by writing helper methods in . rails-app/app/controllers/application_controller.rb helper_method , session[ ] @user = User.find(session[ ]) !!current_user redirect_to login_path logged_in? < ActionController::Base class ApplicationController :logged_in? :current_user def current_user if :user_id :user_id end end def logged_in? end def authorized unless end end Here we’ve defined a few helper methods for use in our controllers and views. looks for a value in the key of the cookie-hash. If there is one, the corresponding user instance will be returned. ApplicationController#current_user :user_id session Otherwise, the return value is . coerces the return value of into a Boolean by use of a double-bang. nil #logged_in? current_user will trigger a redirect to the login page unless a user is logged in (that is, unless a value of exists and it matches the value of an id of an existing user) #authorized session[:user_id] Authorization in Controllers The callback method can help us make short work of using our authorization methods. In our , we'll add: before_action UsersController before_action , [ ] ... < ApplicationController class UsersController :authorized only: :show end With this line, the application will check to see if a user is logged in and redirect to the login path if they aren’t before the action is even fired. But the fun doesn't stop here. We can leverage our authorization helper methods to conditionally render our views! #show Authorization in Views In , let's add a login/logout button below our view template. That way, it will appear on any pages we add to our application. rails-app/app/views/layouts/application.html.erb Recall that in is where the templates corresponding to our controller actions get rendered. <%= yield %> application.html.erb <!DOCTYPE html> <html> ... <body> <%= %> <br> <% logged_in? %> <%= button_to , sessions_path, %> <% %> <%= button_to , login_path, %> <% %> < > yield if "Logout" method: :delete else "Login Page" method: :get end /body> </html Since we defined the helper method and passed as an argument to in our , we are able to use it in our views. This bit of renders a logout button if a user is logged in, and vice versa. #logged_in? :logged_in? helper_method ApplicationController erb We can get even more specific. Since we have a helper method that returns the user of the current session, we can render custom content for that user. current_user On the page, we can make it so that a user sees special content if they're on their own show page. rails-app/app/views/users/show.html.erb <h1>Welcome to the page of <%= @user.username %>< 3> <% % /h2> <% if current_user == @user %> <h3>This is my page!!!</h end Logging Out Every good story has to come to an end. When a user logs out, they are essentially ending their . One basic way of ending a user’s session is to set the value of to . We'll add the following action to our to do so. session session[:user_id] nil SessionsController ... session[ ] = redirect_to login_path < ApplicationController class SessionsController def destroy :user_id nil end end If you’re the observant type, you’ll have noticed that the logout button we created last section makes the HTTP request that will be routed to this action. With that action, the session cookie will cease to know about the user and the user will not be authorized in the application. Conclusion And that’s all it takes to build out basic authentication and authorization in a Rails application with ! When we authenticate a user, we check to see they are who they say they are. We facilitate authentication in a web application through sign up and sign/log in forms. To make use of authentication, we track user state in a session cookie and use that cookie to perform authorization before relevant actions in our application. bcrypt helps us implement authentication by giving us a means of securely storing and cross-referencing authentication factors (like passwords) in our database. To authorize users, we write helper methods that use some of those means as well as the built-in Rails sessions cookie to check user state and react accordingly. bcrypt Now that you have some idea of how it works, try to implement it yourself! When you’re comfortable using , break out the big guns like and try again. Authentication and authorization are essential parts of secure web applications. bcrypt devise We'll all be better off if you use them. And never store plain text passwords in a database.