我最近将我的应用程序升级到Rails 4.我一直在使用omniauth上的自定义openid端口对用户进行身份验证。
控制器(Omniauth Callbacks)
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def openid
@user = User.where(provider: auth_hash["provider"], uid: auth_hash["uid"]).first_or_initialize
@user.name = auth_hash["information"]["name"]
@user.email = auth_hash["information"]["email"]
@user.save!
sign_in_and_redirect @user, :event => :authentication
end
protected
def auth_hash
request.env['omniauth.auth']
end
end
路线
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
devise_scope :user do
get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session
get 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session
end
root :to => "users#front"
[...]
问题
在extern服务中正确登录后,用户将被重定向回OmniauthCallback#openid
。正确创建用户没有任何问题。之后,用户被重定向到root而没有任何问题。但到那时他还没有登录!
我的会话也正确存储在数据库中。我没有收到任何错误,它只是在sign_in_and_redirect @user, :event => :authentication
处不起作用。如何正确地将会话绑定到用户?
更新
使用Cookie来存储会话而不是数据库无法解决
使用sign_in @user
并重新加载页面无法解决
使用@user.save
代替@user.save!
无法解决问题。
我很感激任何想法。
答案 0 :(得分:2)
我终于搞清楚了。我在&#34; sign_in_and_redirect @ user&#34;之前将此行添加到我的oauth回调方法中:
session[:user_id] = @user.id
之后,正确设置current_user。希望这有助于某人。