Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Redmine - Can't verify authenticity token results in a 422 error

I'm working on a plugin for the Redmine platform and I would like to attach a file to a document (basically uploading a file) using a link instead of a form, to do this I'm creating POST requests inside a method.

I followed the instructions here, I set the content type to application/octet-stream as requested then I put the file content in the request body.

I read a lot of posts on this website and I know this has been frequently asked but I can't manage to do my request correctly tough, I'm still getting the error. Here is my code:

uri = URI.parse("http://<my_server_IP_address>:3000/uploads.js")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.path, initheader = {'X-CSRF-Token' => form_authenticity_token, 'Content-Type' => 'application/octet-stream'})
file = File.new("/home/testFile.txt", 'rb')
request.body = file.read
@response = http.request(request)

As you can see, I set the CSRF token in the header using the form_authenticity_token method but I'm still getting a 422 error.

Filter chain halted as :verify_authenticity_token rendered or redirected
Completed 422 Unprocessable Entity in 4.7ms (ActiveRecord: 0.0ms)

I also tried to put skip_before_filter :verify_authenticity_token at the beggining of my controller although it's not recommended, but it's not working neither.

Do you have an idea what's wrong here?

Note: I'm working with Rails 3.2.16, Ruby 1.9.3-p392 and Redmine 2.4.2

like image 881
Shredator Avatar asked Nov 02 '22 02:11

Shredator


1 Answers

Did you mean to POST to "uploads.js" not "uploads.json"?

uri = URI.parse("http://<my_server_IP_address>:3000/uploads.js")

The docs indicate you POST to either uploads.json or uploads.xml seemingly based on the content format you want to receive in response.

(would have made a comment to your question, but I don't yet have the karma for that)

like image 68
Rhizzakanizza Avatar answered Nov 15 '22 05:11

Rhizzakanizza