0
0

More than 3 years have passed since last update.

【Rails Apiモード + devise】ログイン状態が保持されない時の解決法

Posted at

Rails Apiモード + Devise で認証機能を作成。
Session + Cookieでログイン状態を保持するような仕様にしたいが、ブラウザをリロード等するとログイン状態が保持されていないことがわかった。

問題のソースコード

sessions_controller.rb
class Api::V1::Auth::SessionsController < Api::V1::ApplicationController
  before_action :require_no_authentication, only: [:create]

  # POST /api/v1/auth/login
  def create
    user = User.find_for_database_authentication(email: user_params[:email])

    if user.nil?
      return render json: { errors: { message: 'アカウントが見つかりませんでした' } }, status: :not_found
    end

    if user.valid_password?(user_params[:password])
      sign_in user
      render json: { data: user }, status: :ok
    else
      render json: { errors: { message: 'アドレスまたはパスワードが違います' } }, status: :unauthorized
    end
  end

  # DELETE /api/v1/auth/logout
  def destroy
    sign_out current_user
    render json: { message: 'ログアウトしました' }, status: :ok
  end

  private

  def user_params
    params.require(:user).permit(:email, :password)
  end
end

解決法

そもそもCookieが設定されていなかった。
Rails Apiモードでは、デフォルトの設定でsessionが使えないようになっているのでそれが原因だった。sessionを使えるようにするために追記。(こちらの記事を参考にさせていただきました)

application.rb
    config.middleware.use ActionDispatch::Cookies
    config.middleware.use ActionDispatch::Session::CookieStore
    config.middleware.use ActionDispatch::ContentSecurityPolicy::Middleware

サーバーを再起動して、再びログインすると、(ディベロッパーツールなどで確認)_session_idというCookieが設定されていた。ページを再読込してもログイン状態は保持されていた。

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