こんにちは。Takitaです。
Rails5とdevisetokenauthでAPI認証機能を作成した手順をまとめました。
今回は以下のような要件で作ります。
- 管理画面はRailsでviewも作成する
- ユーザー画面はSPAにするのでRailsではAPIを提供する
- 新規登録項目は、email, password, nameの3つ
Rails (5.2.0.rc1 )
devise (4.3.0)
devise_token_auth (0.1.42)
# Gemfile
+# CORS
+gem 'rack-cors'
# config/initializers/cors.rb 新規ファイル
module AppName
class Application < Rails::Application
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/api/*',
headers: :any,
expose: %i[access-token expiry token-type uid client],
methods: %i[get post options delete put]
end
end
end
end
GitHub - ryanb/letter_opener: Preview mail in the browser instead of sending. の準備をしておいてください。
以下を参考にすると良いでしょう。
rocketdash/Gemfile at develop · kajitz/rocketdash · GitHub
rocketdash/development.rb at develop · kajitz/rocketdash · GitHub
rocketdash/routes.rb at develop · kajitz/rocketdash · GitHub
# Gemfile
# Authentication
+gem 'devise'
+gem 'devise_token_auth'
+gem 'omniauth'
$ rails g devise_token_auth:install User auth
$ rails db:migrate
個人的にnameなどのカラムは最初に持ってきたいので少し手直ししました。
# db/migrate/20180220051550_devise_token_auth_create_users.rb
class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name
t.string :email, null: false, default: ''
## Required
省略
app/controllers/application_controller.rb
は管理画面用にして、API用のコントローラーを作成します。
# app/controllers/api/v1/base_controller.rb
class Api::V1::BaseController < ActionController::Base
include DeviseTokenAuth::Concerns::SetUserByToken
protect_from_forgery with: :null_session # トークン認証のためCSRFは使わない
end
deviseの他のコントローラーの継承元に base_controller.rb
を指定します。
# config/initializers/devise.rb
Devise.setup do |config|
+config.parent_controller = 'Api::V1::BaseController'
end
refs: Change Devise parent controller (Example)
name
を追加するapp/controllers/api/v1/auth/registrations_controller.rb
を新規追加します。
# app/controllers/api/v1/auth/registrations_controller.rb
class Api::V1::Auth::RegistrationsController < DeviseTokenAuth::RegistrationsController
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
end
end
refs: GitHub - plataformatec/devise: Flexible authentication solution for Rails with Warden.
新規登録は上記のコントローラーを使うことをルーティングで明示します。
# config/routes.rb
Rails.application.routes.draw do
mount_devise_token_auth_for User.name, at: 'api/v1/auth', controllers: {
registrations: 'api/v1/auth/registrations'
}
end
http://localhost:3000/api/v1/auth
にPOSTリクエストを投げます。
curl
でもいいのですが、今回はPostmanを利用してリクエストを投げました。
idが異なりますが、以下のようなレスポンスが返れば成功です。
http://localhost:3000/letter_opener/
を開きメールを確認しましょう。
アカウントを有効化するをクリックすれば登録新規登録が完了します。
http://localhost:3000/api/v1/auth/sign_in
にPOSTリクエストを投げます。
Gyazo - f35a3d7d340a6813c09ec345a414c544.png
今後はレスポンスヘッダーにある access-token, client, uid
を利用して、ユーザー情報の取得や更新、パスワード変更などを行うことができます。
devisetokenauth でAPIを作成する方法は色んなブログにもあるのですが、
deviseの親コントローラーを指定したりと本家のドキュメントを見ながら実装しました。
気が向けば他の部分も書こうと思います・・・