LoginSignup
5
1

More than 3 years have passed since last update.

omniauthを使った認証時にsessionが消える時の対処法

Last updated at Posted at 2020-03-08

事象

auth0とomniauthを利用して認証処理を作成した。
omniauthの以下のフローがあるが、2の時点では保持しているsessionが、3になるとnilとなってしまい、ログインできないという事象が発生した。
1. プロバイダー側で認証後、railsアプリケーションのcallback関数呼び出し
2. callback関数で諸々処理し、画面にredirect
3. 画面に対応するcontrollerで処理後、画面表示

さらに、ログインできたアカウントが一つ、ログインできなかったアカウントが3つという状態もあり、原因特定に時間がかかった。

環境

  • Ruby 2.7.0
  • Rails 6.0.2.1
  • omniauth 1.9.0
  • omniauth-auth0 2.2.0
  • omniauth-rails_csrf_protection 0.1.2

原因

結論から言うと、3. 画面に対応するcontrollerで処理後、画面表示の段階で、cookieに保存していたsessionが4KBを超えてしまい、sessionが削除されてしまったのが原因。

チュートリアルにある以下のcallback関数で、sessionにrequest.env['omniauth.auth']を保存していたが、これだとサイズがわずかに大きかった。4人中3人が4KBをオーバーし、1人がオーバーしていなかった。

auth0_controller.rb
  def callback
    # This stores all the user information that came from Auth0
    # and the IdP
    session[:userinfo] = request.env['omniauth.auth']

    # Redirect to the URL you want after successful auth
    redirect_to '/dashboard'
  end

対応

request.env['omniauth.auth']infoだけをsessionに保持させるように修正した。

auth0_controller.rb
  def callback
    # This stores all the user information that came from Auth0
    # and the IdP
    session[:userinfo] = request.env['omniauth.auth']['info']

    # Redirect to the URL you want after successful auth
    redirect_to '/dashboard'
  end

参考

5
1
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
5
1