3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rails APIモード devise

Last updated at Posted at 2020-12-06

手順だけ

ターミナル
rails new devise_token_auth --api -d mysql
Gemfile
# トークンベースの認証を行うためのgem
gem 'devise'
gem 'devise_token_auth'
ターミナル
$ bundle install
$ rake db:create
$ rails g devise:install 
$ rails g devise_token_auth:install User auth
$ rails g controller api/auth/registrations
api/auth/registrations_conroller.rb
module Api
  module Auth
    class RegistrationsController < DeviseTokenAuth::RegistrationsController
      private
      def sign_up_params
        params.permit(:first_name, :last_name, :email, :password, :password_confirmation)
      end
      def account_update_params
        params.permit(:first_name, :last_name, :email)
      end
    end
  end
end
config.eb
Rails.application.routes.draw do
  namespace :api do
    mount_devise_token_auth_for 'User', at: 'auth', controllers: {
        registrations: 'api/auth/registrations'
    }
  end
end

リクエストごとに token を新しくしない、変更頻度の設定を決める

config/inizialize/devise_token_auth.rb
  ...
  config.change_headers_on_each_request = false
  config.token_lifespan = 1.month
  config.headers_names = {:'access-token' => 'access-token',
                          :'client' => 'client',
                          :'expiry' => 'expiry',![スクリーンショット 2020-12-06 23.13.12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/239663/9812bd33-0c32-b768-4e99-e2544876a1a7.png)

                          :'uid' => 'uid',
                          :'token-type' => 'token-type' }
 ...
model/user.rb
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

:trackableがあるとSessionのcreateがうまく行かないので一応削除。

postmanで確認してみる

新規登録

スクリーンショット 2020-12-06 22.51.13.png
####ログイン

HeaderにContent-Typeapplication/jsonとして登録
そして確認
スクリーンショット 2020-12-06 23.12.19.png

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?