質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Q&A

解決済

1回答

1040閲覧

[Rails]DeviseとDeviseTokenAuthを利用してaccess_tokenなどのheader情報を取得する方法

yasukun252

総合スコア34

Ruby on Rails 5

Ruby on Rails 5は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Devise

Deviseとは、Ruby-on-Railsの認証機能を追加するプラグインです。

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

1グッド

1クリップ

投稿2023/02/21 02:35

編集2023/02/21 21:03

実現したいこと

RailsとDeviseとDeviseTokenAuthを利用してWebとiOSアプリを開発しております。(RailsはAPIモードではありません。)

  • header情報から、access_token、client、uidを取得したい

前提

Railsを利用してWebとiOSアプリを開発しております。(RailsはAPIモードではありません。)
DeviseとDeviseTokenAuthを導入して認証周りを実装しております。導入までは問題なく進みました。
しかし、header情報は取得できるのですが、access_token、client、uidがheader情報から取得できないため、質問させて頂きました。

全体のソースコードは以下のようになります。

Gemfile

1gem 'devise' 2gem 'devise_token_auth' 3gem 'rack-cors'

routes.rb

1namespace :api, default: { format: :json } do 2 namespace 'v1' do 3 mount_devise_token_auth_for 'User', at: 'auth', controllers: { 4 registrations: "api/v1/auth/registrations", 5 sessions: "api/v1/auth/sessions"} 6 end 7end

config/initializers/cors.rb

1Rails.application.config.middleware.insert_before 0, Rack::Cors do 2 allow do 3 origins 'localhost:3000' 4 resource '/api/v1/*', 5 headers: :any, 6 expose: ['access-token', 'uid', 'client', 'expiry', 'token-type', 'authorization'], 7 methods: [:get, :post, :put, :patch, :delete, :options, :head] 8 end 9end

config/initializers/devise_token_auth.rb

1DeviseTokenAuth.setup do |config| 2 3 config.change_headers_on_each_request = false 4 config.enable_standard_devise_support = true 5 config.token_lifespan = 2.weeks 6 config.token_cost = Rails.env.test? ? 4 : 10 7 config.headers_names = {:'access-token' => 'access-token', 8 :'client' => 'client', 9 :'expiry' => 'expiry', 10 :'uid' => 'uid', 11 :'token-type' => 'token-type', 12 :'authorization' => 'authorization' } 13 14end

Models/user.rb

1class User < ApplicationRecord 2 devise :database_authenticatable, :registerable, 3 :recoverable, :rememberable, :validatable 4 include DeviseTokenAuth::Concerns::User 5 6end

application_controller.rb

1class ApplicationController < ActionController::Base 2 protect_from_forgery with: :null_session, if: -> { request.format.json? } 3end

app/controllers/api/v1/application_controller.rb

1class Api::V1::ApplicationController < ActionController::API 2 include DeviseTokenAuth::Concerns::SetUserByToken 3 protect_from_forgery with: :null_session 4end

app/controllers/api/v1/auth/registrations_controller.rb

1class Api::V1::Auth::RegistrationsController < DeviseTokenAuth::RegistrationsController 2 3 def create 4 resource = build_resource 5 if @resource.save 6 user = User.find_by(email: resource.downcase) 7 render json: { status: 'ok', current_user: current_api_v1_user }. # current_userは取得できる 8 sign_in(user) 9 else 10 render json: { status: 'ng' } 11 end 12 13 private 14 15 def sign_up_params 16 params.require(:registration).permit(:name, :email, :password) 17 end 18end

app/controllers/api/v1/auth/sessions_controller.rb

1class Api::V1::Auth::SessionsController < DeviseTokenAuth::SessionsController 2 def create 3 render json: { status: 'SUCCESS LOGIN', current_user: current_api_v1_user } # current_userはnilになる 4 end

試したこと

コマンドラインでcurlでsign_inするPOSTリクエストを実行しても、リクエストは200 OKとなりますが、access_token、client、uidがheader情報から取得できません。

terminal

1% curl localhost:3000/api/v1/auth/sign_in -X POST -H 'Content-Type: application/json' -d '{"email": "test@example.com","password": "password"}' -i 2HTTP/1.1 200 OK 3X-Frame-Options: SAMEORIGIN 4X-XSS-Protection: 1; mode=block 5X-Content-Type-Options: nosniff 6X-Download-Options: noopen 7X-Permitted-Cross-Domain-Policies: none 8Referrer-Policy: strict-origin-when-cross-origin 9Content-Type: application/json; charset=utf-8 10ETag: W/"dbd384a8d3826bdb8dbc19bf88dd6585" 11Cache-Control: max-age=0, private, must-revalidate 12X-Rack-Dev-Mark-Env: development 13X-Request-Id: 5ec3438d-a6dd-435d-a601-3b9b4ab1855d 14X-Runtime: 0.439754 15Transfer-Encoding: chunked

以上となります。アドバイスなど何卒よろしくお願いいたします。

補足情報(FW/ツールのバージョンなど)

Rails(5.2.8)、ruby(2.6.0)になります。

sho_a5👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yuma.inaura

2023/02/21 11:39

Api::V1::Auth::SessionsController#create を上書きしてるからとかですかね
yasukun252

2023/02/21 11:43

コメントありがとうございます! 確かに、Api::V1::Auth::SessionsController#create を削除したらaccess_token、client、uidが取得できました。しかし、Api::V1::Auth::SessionsController#createは上記のようにrenderで返す実装にしたいのですが、その場合はどのように実装すれば良いでしょうか?
yuma.inaura

2023/02/21 11:53

回答の方に書きました
yasukun252

2023/02/21 12:03

ありがとうございます!
guest

回答1

0

ベストアンサー

Api::V1::Auth::SessionsController#create を上書きして使っているからではないでしょうか。
ちなみに全く認証が行われず、どんなID/パスワードでもログインが成功するようになってたりしないでしょうか。

DeviseTokenAuth::SessionsController の大本の処理をカスタマイズして create に書いてみてはいかがですか。
コードを見る限りは render_create_success を任意の処理に書き換えると良いように見えます。

力技ではあるので、 もしdevise-token-auth でもっと良いやり方が用意されている場合はそちらの方が良いかも知れませんが

rb

1 def create 2 # Check 3 field = (resource_params.keys.map(&:to_sym) & resource_class.authentication_keys).first 4 5 @resource = nil 6 if field 7 q_value = get_case_insensitive_field_from_resource_params(field) 8 9 @resource = find_resource(field, q_value) 10 end 11 12 if @resource && valid_params?(field, q_value) && (!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?) 13 valid_password = @resource.valid_password?(resource_params[:password]) 14 if (@resource.respond_to?(:valid_for_authentication?) && !@resource.valid_for_authentication? { valid_password }) || !valid_password 15 return render_create_error_bad_credentials 16 end 17 18 create_and_assign_token 19 20 sign_in(:user, @resource, store: false, bypass: false) 21 22 yield @resource if block_given? 23 24 # render_create_success 25 render json: { status: 'SUCCESS LOGIN' }  26 elsif @resource && !(!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?) 27 if @resource.respond_to?(:locked_at) && @resource.locked_at 28 render_create_error_account_locked 29 else 30 render_create_error_not_confirmed 31 end 32 else 33 render_create_error_bad_credentials 34 end 35 end

https://github.com/lynndylanhurley/devise_token_auth/blob/master/app/controllers/devise_token_auth/sessions_controller.rb#L13

投稿2023/02/21 11:53

yuma.inaura

総合スコア1451

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問