Ruby on Rails Api authentication with rails cookie session.
Tags: rails, cookie
Published: 2023-12-10 03:55:45

## Backend (Rails API)

### Step 1: Create a New Rails API Project

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

```bash
rails new your_api_project_name --api -d postgresql
cd your_api_project_name
```

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:

```ruby
gem 'devise_token_auth'
```

Then, execute the following commands:

```bash
bundle install
rails generate devise:install
rails generate devise_token_auth:install
rails db:migrate
```

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:

```ruby
class ApplicationController < ActionController::API
  include ActionController::Cookies
  include DeviseTokenAuth::Concerns::SetUserByToken
end
```

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:

```ruby
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
```

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:

```ruby
config.cookie_enabled = true
config.cookie_attributes = {
  httponly: true,
  encrypt: true,
  same_site: :strict,
  secure: true
}
```

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

```ruby
mount_devise_token_auth_for 'User', at: 'auth'
```

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:

```bash
yarn add axios
```

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

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

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!