We are planning interaction between php script to ruby on rails server and vice-versa.
Whenever I do curl post data from php script, on rails server notification displays - "Can't verify CSRF token authenticity"
.
I am passing authenticity_token
in post parameters. We need to how to use this token in secure manner on rails server.
<?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 code -
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
Can anyone tell us how can we keep our authenticity_token random ,consistent and secure between two servers (php and ruby on rails).
If are using the rails controller as an API, protecting with CSRF tokens doesn't make sense. As the name Cross-Site Request Forgery tokens say, they prevent your app from being accessed from anywhere other than the views generated by the same web app.
So, you should disable CSRF in your case and use the authenticity token.
Answering your question with how to securely use this authenticity token on rails app, if you have any user management, assign authenticity tokens to users and find user with a sent token and you know if that user is allowed to make that request. If you don't have a user management, create a database table for authenticity tokens and validate the requests based on what you have in database.
You could write a custom before_filter
in application_controller and perform the authentication or authorization based on the authenticity_token in the request.
P.S, if you are worried about the authenticity_token being visible for attackers in the network while sending requests, use https.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With