0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

deviseとJwtで認証を作りたいけど....

Last updated at Posted at 2025-08-19

ログインができない

  • バージョン
    • Rails 7.1.5.2
    • devise-jwt 0.12.1

この記事を参考にして、認証回りを作成していました。

registrations_controller.rbの変更

※app\backend\app\controllers\api\v1\users\sessions_controller.rb
sigin_up_paramsを追記

class Api::V1::Users::RegistrationsController < Devise::RegistrationsController
  include RackSessionFix
  respond_to :json

  private

  def respond_with(resource, _opts = {})
    register_success && return if resource.persisted?

    register_failed
  end

  def register_success
    render json: { message: 'Signed up successfully.', user: resource }, status: :ok
  end

  def register_failed
    render json: {
      message: "Signed up failure.",
      errors: resource.errors.full_messages
    }, status: :unprocessable_entity
  end

+  def sign_up_params
+    params.require(:user).permit(:email, :password, :password_confirmation)
+  end

end

Postmanでリクエストを送信(signup)

http://localhost:3000/api/v1/users
に対してリクエストを送信、ユーザが登録されている。
image.png

Postmanでリクエストを送信(login)

image.png

ログインすることができない.....

一応Railsコンソールで保存されているか確認
image.png

登録はされているらしい。。

session_controller.rbのcreateメソッドをオーバーライドすると確かにUserを返すことができるのだが、トークンが付与されていない....

記事のコードと違う箇所

app\backend\config\routes.rb

Rails.application.routes.draw do
...
  namespace :api do
    namespace :v1 do
      devise_for :admins,controllers: {
          sessions: 'api/v1/admins/sessions',
          registrations: 'api/v1/admins/registrations'
        }
      devise_for :users, controllers: {
        sessions: 'api/v1/users/sessions',
        registrations: 'api/v1/users/registrations'
     }
    end
  end
 end
...

app\backend\config\initializers\devise.rb

  config.jwt do |jwt|
    jwt.secret = Rails.application.credentials.fetch(:secret_key_base)
    jwt.dispatch_requests = [
      ['POST', %r{^/api/v1/users/sign_in$}]
    ]
    jwt.revocation_requests = [
      ['DELETE', %r{^/api/v1/users/sign_out$}]
    ]
    jwt.expiration_time = 30.minutes.to_i
  end

Userモデルに問題が??

class User < ApplicationRecord
  devise :database_authenticatable,
          :registerable,
-         :recoverable, 
-         :rememberable, 
         :validatable,
         :jwt_authenticatable, jwt_revocation_strategy: JwtDenylist
end

rememberableはクッキーを使うため、今回は必要ない。

しかしデフォルトでdeviseはrememberable_optionsを呼ぶため、NoMethodErrorが起きる。

なのでsessionコントローラーのcreateを上書きする。

ちゃんとJsonは返ってきたが、JWTトークンが付与されていない。。。。
image.png

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?