请求 - 从 php 服务器到 rails 服务器上的 ruby 的响应。 CSRF 令牌问题

Request - Response from php server to ruby on rails server. CSRF token issue

我们正在计划 php 脚本与 rails 服务器上的 ruby 之间的交互,反之亦然。

每当我从 php 脚本卷曲 post 数据时,rails 服务器通知显示 - "Can't verify CSRF token authenticity"

我在 post 参数中传递 authenticity_token。我们需要了解如何在 rails 服务器上以安全的方式使用此令牌。

<?php

    class active_merchant{    
        private $endpoint_url;      // server address or url where data is to be posted.
        private $params;            // form fields
        private $fields_count;      // count of fields in credit card

        public function __construct(){

            $this->endpoint_url = "http://localhost:8080/activemerchant/index";
            $token = md5('random');
            $this->params = array('name'=>'test','authenticity_token'=>$token);

        }

        /*  function curl_post
            makes a curl post to the end point url
            global variables 
             */

        public function curl_post(){

            try{

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $this->endpoint_url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->params));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
                $response = curl_exec($ch);

                print_r($response);
                //return $response;

            }catch(Exception $e){
                throw new Exception($e->getMessage(),$e->getCode(),$e->gtLine());
            }

        }

    }

    $active_merchant = new active_merchant();
    $active_merchant->curl_post();    
?>      

Rails 代码 -

class ActivemerchantController < ApplicationController
protect_from_forgery except: :index
  def index
    Rails.logger.debug params.inspect
    puts params.inspect
    self.response_body = "Hello, world!"
  end
end

谁能告诉我们如何在两个服务器(php 和 rails 上的 ruby)之间保持我们的 authenticity_token 随机、一致和安全。

如果 Rails 应用程序用作 API 服务器,则只需在适当的控制器中添加 protect_from_forgery with: :null_session

如果将 rails 控制器用作 API,则使用 CSRF 令牌进行保护没有任何意义。正如跨站点请求伪造令牌的名称所说,它们可以防止您的应用程序从同一网络应用程序生成的视图以外的任何地方访问。

因此,您应该在您的情况下禁用 CSRF 并使用真实性令牌。

回答您关于如何在 rails 应用程序上安全使用此真实性令牌的问题,如果您有任何用户管理,请将真实性令牌分配给用户并找到具有已发送令牌的用户,您知道该用户是否是允许提出该请求。如果您没有用户管理,请为真实性令牌创建一个数据库 table,并根据您在数据库中的内容验证请求。

可以在application_controller中写一个自定义的before_filter,根据请求中的authenticity_token进行认证或授权。

P.S,如果您担心 authenticity_token 在发送请求时对网络中的攻击者可见,请使用 https。