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

Sas*_*shi 7 php ruby curl ruby-on-rails ruby-on-rails-3

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

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

我在传递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();    
?>      
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我们如何在两台服务器(php和ruby on rails)之间保持我们的authenticity_token随机,一致和安全.

aBa*_*boy 1

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

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

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

您可以在application_controller中编写自定义before_filter,并根据请求中的authenticity_token进行身份验证或授权。

PS,如果您担心发送请求时网络中的攻击者可以看到authenticity_token,请使用https。