概要
Rails6 に Device Token Auth を使ってトークン認証を導入する方法を書いています。
プロジェクトの作成
まず、適当な Rails プロジェクトを作成します。
rails new myproject
cd myproject
プロジェクトを作成したら、Gemfileを開いて必要なライブラリを追加します。
追加後はbundle installします。
gem 'devise'
gem 'devise_token_auth'
Devise のセットアップ
トークン認証のためのセットアップを行なっていきます。
次のコマンドを順番どおりに実行します。
bin/rails g devise:install
bin/rails g devise_token_auth:install User auth
最後のコマンドのUserとauthは変更可能です。
Userは devise のユーザー認証を実装しているモデル名を代わりに指定できます。
authは認証時のルートパスを指定しています。
コマンド実行後に生成されるmodels/user.rbを開いてください。
クラスメソッドdeviseの引数にある:trackableを取り除きます。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
include DeviseTokenAuth::Concerns::User
end
devise_token_authのジェネレータによって生成されるマイグレーションファイルはtrackableに必要なカラムを含んでいません。
よってモデルから取り除くか、マイグレーションファイルに必要なカラムを追記しないとこの後実行時にエラーが発生してしまいます。
すべて終わればマイグレーションを実行して準備完了です。
bin/rails db:migrate
テストしてみる
トークンが取得できるか実際に試してみます。
その前にユーザーと簡単なログイン後のページを作っておきます。
bin/rails r 'User.create(email: "test@example.com", password: "password")'
bin/rails g controller home index
class HomeController < ApplicationController
before_action :authenticate_user!
def index
render json: 'ok'
end
end
bin/rails sで立ち上げたら curl でアクセスしてみます。
まずはログインから。
curl -i http://localhost:3000/auth/sign_in -d '{"email": "test@example.com", "password": "password"}' -H 'content-type:application/json'
-iオプションをつけて実行したので、レスポンスヘッダも出力されているはずです。
ログインに成功していればaccess-tokenやclient,uuidが含まれています。
最後に、ログイン後のページにアクセスしてみます。
先ほど取得したトークンを使えば成功するはずです。
curl http://localhost:3000/home -H 'access-token: <ACCESS_TOKEN>' -H 'client: <CLIENT>' -h 'uid: test@example.com'
ok
おしまい