大家好。
我试图用rails和react中的前台来实现与Facebook和Google的omniauth.身份验证是由devise token auth gem处理的,身份验证工作正常,因为我可以签署一个用户,并使用Axios拦截头和存储信息,我需要让他在网站上导航,但我面临一个不同的问题。
class Api::V1::Users::OmniauthCallbacksController < DeviseTokenAuth::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
sign_in @user
# Normal case with no headers
redirect_to '/dashboard'
# manually trying to render a json
# headers = @user.create_new_auth_token
# response = Hash.new
# response["user"] = @user
# response["headers"] = headers
# render json: {response: response, status: :ok }
else
session['devise.facebook_data'] = request.env['omniauth.auth']
redirect_to new_user_registration_url
end
end
end
module DeviseTokenAuthReactOmniauth
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options
config.middleware.insert_before 0, Rack::Cors, debug: true, logger: (-> { Rails.logger }) do
allow do
origins '*'
resource '*',
headers: :any,
expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :options, :delete, :put]
end
end
end
end
当我运行 bundle exec rake 中间件时,我看到 rack-cors 是在 Webpacker 之后。
use Webpacker::DevServerProxy
use Rack::Cors
match '/api/v1/auth/facebook', to: 'api/v1/users/omniauth_callbacks#facebook', via: [:get, :post]
我最终得到一个RuntimeError (No resource_class found)。在这种情况下,似乎命名空间和类没有被识别。我试着在我的命名空间和类上添加一个前缀。omniauth.rb (OmniAuth.config.path_prefix = "apiv1auth")文件,但没有任何变化。
这是我项目的链接,以便更好地理解。https:/github.comcroisle-devis-token-auth-react-omniauth。
我是一个新手,但我认为如果我找到一种方法来返回一个JSON,被我的拦截器捕获,这将解决我的问题,我的用户将被重定向到仪表板,但我不能看到它,我希望我的解释是不混淆,但如果不告诉我什么是不明白的,所以任何帮助是欢迎的。谢谢你的帮助
我只是有一个类似的问题,基本上收集了一些用户数据,然后使用axios调用一个rails控制器,然后将重定向到一个Auth供应商将导致一个 CORS 错误。
为了避免这个问题,我没有让rails控制器来做重定向,而是给客户端发送一个成功的响应,说服务器验证了用户数据,一些加密的东西被添加到会话中,然后在 轴心 我将用户发送给认证提供者,方法是使用 window.location.href
.
类似于:
axios({
method: 'post',
url: '/signup/user',
data: data,
})
.then(response => {
// check if response is successful then call the omniauth endpoint
window.location.href = '/auth/facebook'
})