通过Rack-CORS根据来源限制客户端请求

时间:2015-06-18 14:36:36

标签: ruby-on-rails ruby api cross-domain cors

我有一个Rails 4 API,用于在客户端请求期间检查访问令牌。我启用了rack-cors gem并进行了以下设置:

配置/ application.rb中:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
  end
end

我有一个名为ApiApp的模型,用于存储访问令牌。有人担心将应用程序打开到任何来源会带来安全风险。有没有办法在ApiApp中存储所需的Origin,例如“test.com”,并且能够通过rack-cors设置检查它是否与每个请求匹配?

应用程序/控制器/ API / V1 / api_controller.rb:

module Api
  module V1
    class ApiController < ApplicationController
      respond_to :json
      before_filter :restrict_access

      private

      def restrict_access
        api_app = ApiApp.find_by_access_token(params[:access_token])
        # need to check that the origin is whitelisted via rack-cors
        head :unauthorized unless api_app
      end
    end
  end
end

我担心rack-cors配置加载一次并且无法访问ApiApp数据。

示例请求:

https://hello.com/api/v1/products?access_token=7b9f3cddd3914a6f45fa692997fe6dc9

感谢您的任何想法。我很感激被指向显示使用rack-cors进行原点检查的示例,检查(可能是标题)的替代方法或任何不必要的参数。

0 个答案:

没有答案