dlindahl / omniauth-cas

A CAS OmniAuth Strategy
MIT License
88 stars 79 forks source link

CAS authorizes then unauthorizes login on first attempt #64

Open eltiffster opened 3 years ago

eltiffster commented 3 years ago

I'm getting a strange error when trying to log in using CAS. When I first try to log in with CAS, I get redirected back to /users/sign_in. Looking at the logs, it seems like the user is signed in and redirected, but the current_user is not set properly.

I would like to either find and update a user if they already exist, or create a new user if not. This is what I see in the logs:

Started GET "/users/auth/cas/callback?...
Processing by OmniauthCallbacksController#cas as HTML
Redirected to http://example.com/dashboard
Processing by DashboardController#show as HTML
Completed 401 Unauthorized in 12ms (ActiveRecord: 0.9ms)
Started GET "/users/sign_in"...

However, if I click "Sign in with CAS" again, I am signed in and redirected as expected.

In my OmniauthCallbacksController, I have:

  def cas
    @user = User.from_omniauth(request.env["omniauth.auth"])
     if @user.persisted?
        sign_in_and_redirect @user, event: :authentication
        set_flash_message :notice, :success, kind: "CAS"
     end
  end

In DashboardController, I have before_action :authenticate_user!

And in my User model:

  def self.from_omniauth(auth)
    if User.where(uid: auth.extra.uid).present?
        user = User.find_by(uid: auth.extra.uid)
    # Find a user if they were previously saved using email and password
    elsif User.where(email: auth.extra.mail).present?
        user = User.find_by(email: auth.extra.mail)
    else
        user = User.new
    end
    user.provider = auth.provider
    user.uid = auth.extra.uid
    user.display_name = auth.extra.cn
    user.email = auth.extra.mail
    user.password = Devise.friendly_token[0,20]
    user.save!
    user
  end

If I split up sign_in_and_redirect into seperate statements like so:

if @user.persisted?
   sign_in(@user)
   Rails.logger.debug "current_user = #{current_user}"
   Rails.logger.debug "user_signed_in? = #{user_signed_in?}"
   set_flash_message :notice, :success, kind: "CAS"
   redirect_to dashboard_path
end

I get the same result but see this in the logs:

current_user = user@email.com
user_signed_in? = true

Which makes me think this is an issue with sessions and redirection rather than signing in. I tried deleting a user and re-adding them to see if the issue only happens with existing users, but the issue persists with newly-created users as well.