Rails 6 に devise_token_auth をインストールする


はじめに

Rails 6 に devise_token_auth をインストールするためのメモ。

環境

$ hostnamectl status
   Static hostname: ---
         Icon name: computer-container
           Chassis: container
        Machine ID: ---
           Boot ID: ---
    Virtualization: lxc
  Operating System: Ubuntu 20.04.2 LTS
            Kernel: Linux 5.4.0-67-generic
      Architecture: x86-64
$ ruby -v
ruby 2.7.0p0 (2019-12-25 revision 647ee6f091) [x86_64-linux-gnu]

インストール

Gemfile に追加。

$ vim Gemfile

追記内容は以下。

gem 'devise'
gem 'devise_token_auth'
gem 'rack-cors'

Bundle を利用して、 devise_token_auth をインストール。

$ bundle install

テーブルを作成。

$ bundle exec rake db:create

ジェネレータでテンプレートを生成。

$ bundle exec rails generate devise:install \
  && bundle exec rails generate devise_token_auth:install User auth

生成したマイグレーションファイルを編集。

$ vim db/migrate/<生成日時>_devise_token_auth_create_users.rb

User Infoの下あたりに下記設定を追記。

## Trackable
t.integer  :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string   :current_sign_in_ip
t.string   :last_sign_in_ip

マイグレーションを実施。

$ bundle exec rake db:migrate

devise_token_auth.rb を下記内容に編集。

$ vim config/initializers/devise_token_auth.rb
DeviseTokenAuth.setup do |config|
  config.change_headers_on_each_request = false
  config.token_lifespan = 2.weeks
  config.headers_names = {:'access-token' => 'access-token',
                          :'client' => 'client',
                          :'expiry' => 'expiry',
                          :'uid' => 'uid',
                          :'token-type' => 'token-type' }
end

application_controller.rbを下記内容に編集。

$ vim app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
  skip_before_action :verify_authenticity_token, if: :devise_controller?
end

routes.rbを下記内容に編集。

$ vim config/routes.rb
Rails.application.routes.draw do
  namespace :api do
    scope :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
    end
  end
end

動作確認 - サインアップ

アプリケーションサーバを起動。

$ bundle exec rails server -p 3000 -b '0.0.0.0' -e development

サインアップのリクエストを送る。

$ curl -X POST\
  -H "content-type:application/json" \
  -d '{"email":"example@long-in.net", "password":"password", "password_confirmation": "password"}' \
  localhost:3000/api/v1/auth

サインアップが成功すると下記レスポンスが返ってくる。

{
  "status": "success",
  "data": {
    "id": 1,
    "provider": "email",
    "uid": "example@long-in.net",
    "allow_password_change": false,
    "name": null,
    "nickname": null,
    "image": null,
    "email": "example@long-in.net",
    "created_at": "2021-10-10T16:48:04.315Z",
    "updated_at": "2021-10-10T16:48:04.389Z"
  }
}

動作確認 - サインイン

サインインのリクエストを送る。

$ curl -X POST \
  -H "content-type:application/json" \
  -d '{"email":"example@long-in.net", "password":"password"}' \
  localhost:3000/api/v1/auth/sign_in 

サインインが成功すると下記レスポンスが返ってくる。

{
  "data": {
    "email": "example@long-in.net",
    "uid": "example@long-in.net",
    "id": 1,
    "provider": "email",
    "allow_password_change": false,
    "name": null,
    "nickname": null,
    "image": null
  }
}

動作確認 - パスワード変更

パスワード変更のリクエストを送る。

$ curl -X PUT \
  -H "content-type:application/json" \
  -H "uid: example@long-in.net" \
  -H "access-token: X_nwavrp7azT3IaZqhnJww" \
  -H "client: Tlp6urWDyi55YuU7DCLgGA" \
  -d '{"password":"new_password", "password_confirmation": "new_password"}' \
  localhost:3000/api/v1/auth/password

パスワード変更が成功すると下記レスポンスが返ってくる。

{
  "success": true,
  "data": {
    "email": "example@long-in.net",
    "uid": "example@long-in.net",
    "id": 1,
    "provider": "email",
    "allow_password_change": false,
    "name": null,
    "nickname": null,
    "image": null,
    "created_at": "2021-10-10T16:48:04.315Z",
    "updated_at": "2021-10-10T17:02:30.374Z"
  },
  "message": "Your password has been successfully updated."
}

参考サイト

devise token authを使用してRails APIを作成する