Search⌘ K
AI Features

Create Tokens

Explore how to create JWT authentication tokens in a Rails API by setting up a tokens controller with a secure create action. Understand how to hash and verify passwords using bcrypt and implement tests to ensure proper token generation and unauthorized access handling.

We only need the POST request for the tokens controller as we will not need to view, edit, or delete the tokens. Thus, we will just be working on the create action.

Add routes

We will modify the route a little to respect the REST conventions. The config/routes.rb should look like this:

Ruby
Rails.application.routes.draw do
namespace :api, defaults: { format: :json } do
namespace :v1 do
resources :users, only: %i[show create update destroy]
resources :tokens, only: [:create]
end
end
end

Add tests

We will build functional tests before going any further. The desired behavior is as follows:

  • The user receives a token if they send a valid email/password pair.
  • Otherwise, the server responds
...