DEV Community

Seamoon Pandey
Seamoon Pandey

Posted on • Updated on

Ruby on Rails Api authentication with rails cookie session.

Backend (Rails API)

Step 1: Create a New Rails API Project

To start building your Rails API, open your terminal and run:

rails new your_api_project_name --api -d postgresql
cd your_api_project_name
Enter fullscreen mode Exit fullscreen mode

Explanation: This command initializes a new Rails API project, enabling API-only functionality and using PostgreSQL as the database.

Step 2: Integrate Devise and Devise Token Auth

Add Devise and Devise Token Auth to your Gemfile:

gem 'devise_token_auth'
Enter fullscreen mode Exit fullscreen mode

Then, execute the following commands:

bundle install
rails generate devise:install
rails generate devise_token_auth:install
rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Explanation: These commands install and configure Devise along with Devise Token Auth. They set up authentication for your User model and create the necessary files and database tables.

Step 3: Configure ApplicationController

In app/controllers/application_controller.rb, add the following lines:

class ApplicationController < ActionController::API
  include ActionController::Cookies
  include DeviseTokenAuth::Concerns::SetUserByToken
end
Enter fullscreen mode Exit fullscreen mode

Explanation: This configures your ApplicationController to include modules for handling cookies and setting the user based on the authentication token.

Step 4: Configure Application

In config/application.rb, add the following lines:

config.api_only = true
config.session_store :cookie_store, key: '_your_api_session', httponly: true, same_site: :strict, secure: true
config.middleware.use ActionDispatch::Cookies
config.middleware.use config.session_store, config.session_options
Enter fullscreen mode Exit fullscreen mode

Explanation: These configurations ensure that your API works in an API-only mode, sets up secure cookie storage, and adds necessary middleware.

Step 5: Configure Devise Token Auth

In config/initializers/devise_token_auth.rb, add the following:

config.cookie_enabled = true
config.cookie_attributes = {
  httponly: true,
  encrypt: true,
  same_site: :strict,
  secure: true
}
Enter fullscreen mode Exit fullscreen mode

In config/routes.rb, mount Devise Token Auth for the 'User' model:

mount_devise_token_auth_for 'User', at: 'auth'
Enter fullscreen mode Exit fullscreen mode

Explanation: These configurations enable token authentication and set up cookie attributes for added security.

Frontend (Using Axios)

Step 6: Set Up Axios for Authenticated Requests

Install Axios using:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

Now, when making authenticated requests, use Axios with withCredentials: true:

axios.get('your/api/endpoint', { withCredentials: true })
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });
Enter fullscreen mode Exit fullscreen mode

Explanation: Axios is a popular HTTP client for the browser and Node.js. The withCredentials: true option ensures that cookies are sent with requests, crucial for authentication.

Step 7: Middleware for Authenticated Requests

Consider creating a middleware for handling authentication in your frontend. Middleware can centralize logic for authenticated requests.

Step 8: Manage Authenticated State with a Cookie

Use a logged_in cookie to manage the authenticated state on the client side. Set it to true on login and false on logout or session expiration.

Explanation: This helps keep track of the user's authentication status on the frontend, providing a seamless user experience.


This guide covers the setup of a Rails API with token-based authentication using Devise and Devise Token Auth, along with frontend integration using Axios. Feel free to customize these steps based on your project's specific needs. If you have any questions or need further clarification, Mate, do some more research!

Top comments (0)