3

概括:

我有一个 CORS 问题。我正在尝试从带有 Rails API 的 React 应用程序向 Facebook 进行身份验证。

我的应用程序在 localhost:8080 上运行,我的 api 在 Heroku 上运行。

我能够登录到 facebook 并在回调时创建一个会话,但 facebook 设置的 cookie 没有被omniauth 拾取。我使用omniauth-facebook 客户端身份验证。

我认为问题出在我的机架配置中。当我在 localhost:3000 上运行我的 api 时,它可以工作。

早些时候,我收到了错误csrf-detected,但通过添加 provider_ignores_state: trueomniauth配置解决了这个问题。后来,我发现这xhrFields: { withCredentials: true }是 cors 调用传递 cookie 所必需的。

最后的解决方案:最后,我通过将我的应用程序部署到具有域的 AWS 53example.com并在 Heroku 上的我的 api 上创建 CNAMES 'api.example.com' 来解决这个问题。

解决 CNAMES 需要一天的时间。example.com您可以使用命令 host和 host在终端中测试您的设置api.example.com

另一种解决方案是使用 nginx 作为代理。

版本:

Rails 4.2.2
Omniauth-facebook 3.0.0
Omniauth-oauth2 1.4.0
Rack-cors 0.4.0

问题:

Getting error: no_authorization_code.

路线:

  namespace :api do
    match "/auth/:provider/callback", to: "sessions#create", via: [:get, :post]
    get "/auth/failure", to: "sessions#failure"
    get "/logout", to: "sessions#destroy"

应用程序.rb:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins "localhost:8000", "example.com"
    resource "*",
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options],
      :max_age => 1728000
  end
end

Omniauth.rb:

OmniAuth.config.path_prefix = "/api/auth"

OmniAuth.config.logger = Rails.logger

OmniAuth.config.on_failure = Proc.new { |env|
  OmniAuth::FailureEndpoint.new(env).redirect_to_failure
}

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook,
    Rails.application.secrets.facebook_key,
    Rails.application.secrets.facebook_secret, {
      provider_ignores_state: true,
      client_options: {
        :ssl => { :ca_file => "/usr/lib/ssl/certs/ca-certificates.crt" }
      }
    }
  provider :identity,
    fields: [:email],
    on_failed_registration: lambda { |env|
      Api::IdentitiesController.action(:new).call(env)
    }
end

秘密.yml:

development:
facebook_key: <%= ENV["FACEBOOK_KEY"] %>
facebook_secret: <%= ENV["FACEBOOK_SECRET"] %>

客户:

$.ajax({
  url: http://localhost:3000/api/auth/facebook,
  dataType: "json",
  type: "GET",
  xhrFields: { withCredentials: true },
  success: function(data) {
  }.bind(this),
  error: function(xhr, status, err) {
  }.bind(this)
})

会话控制器:

module Api
  class SessionsController < ApplicationController
    skip_before_action :verify_authenticity_token
    skip_before_action :restrict_access
    skip_after_action :verify_authorized

def create
  user = User.from_omniauth(auth_params)
  session[:user_id] = user.id
  render json: user, status: :ok
end

def destroy
  session[:user_id] = nil
  render json: {}, status: :ok
end

def failure
  render json: { errors: params[:message] }, status: :unauthorized
end

private

def auth_params
  request.env.fetch("omniauth.auth")
end end end

应用控制器:

class ApplicationController < ActionController::Base
  include Pundit
  before_action :restrict_access
  after_action :verify_authorized, :except => :index
  after_action :verify_policy_scoped, :only => :index

    respond_to :json

    protected

    attr_reader :current_user

    # Allows access to current_user in serializators.
    serialization_scope :current_user

    def restrict_access
      authenticate_or_request_with_http_token do |token, options|
      @current_user = User.find_by(token: token)
    end
  end
end
4

3 回答 3

2

我发现我的 Ajax 调用需要包含 xhrFields: { withCredentials: true } 才能将 cookie 传递给omniauth。

这是因为它是一个跨域调用。

有关详细信息,请参阅http://api.jquery.com/jquery.ajax/ 。

于 2015-11-30T17:47:39.217 回答
0

也许 CORS 中间件不适合您。我没有这方面的经验,但也许只是在您的应用程序控制器中添加一个之前的操作,然后执行以下操作......只是为了确保您知道适当的标题存在。

response.headers["Access-Control-Allow-Origin"] = "http://localhost:8080"
于 2015-06-26T23:48:12.463 回答
0

我在使用 Devise 在 Rails 应用程序中执行omniauth 时遇到了同样的问题。最终,对我来说问题是 Facebook 在 7 月初更新了他们的 API,现在它要求你专门询问info_fields参数中的字段。

我会尝试改变你omniauth.rb的包括:

provider :facebook,
 Rails.application.secrets.facebook_key,
 Rails.application.secrets.facebook_secret, {
   :scope => "email, user_birthday",
   :info_fields => "email, user_birthday", #<== this made the difference for me
   provider_ignores_state: true
 }

这是来自提到该问题的设计 wiki 的链接。我知道您没有使用设计,但它可能会有所帮助。https://github.com/plataformatec/devise/wiki/OmniAuth:-概述

于 2015-09-14T16:32:03.763 回答