Authentication in Rails: Sessions and Cookies
There are several different ways authentication is built in Rails. The most common of those methods involve the use of cookies which are stored in the user’s browser. The point of authorization is to make sure that a person who’s making a request to the server is a valid user who is logged in with the requisite permissions to do so.
Cookies store information in HTTP headers and are then stored as plain text in a user’s browser. These cookies can be easily manipulated and set by users, causing major security concerns due to potential data breaches. To keep a potential cookie monster from doing this, the session method is used instead as it behaves like a hash, hiding data in serialized key/value pairs which are configured in:
config/secrets.yml
This data is then stored away as a massive string housed in a single massive cookie called:
_YOUR_RAILS_APP_NAME_session
To prevent tampering with those cookies, Rails creates a signature through the sign method, which takes in a message and a key and then returns a signature in string form as displayed below:
An example of how to implement sessions and cookies in a Rails project in the context of a shopping cart application:
In application_controller.rb:
This declares the cart controller method as a helper, making the cart controller method available to the view.
In products_controller.rb:
In index.html.erb:
Sources:
https://www.theodinproject.com/courses/ruby-on-rails/lessons/sessions-cookies-and-authentication
https://learn.co/lessons/cookies_and_sessions_lab
https://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
https://guides.rubyonrails.org/action_controller_overview.html#session