I had this service working before, with some other fields, but right now i seem not to get it working, and am not quite getting why.
I'm posting the following json to my Rails app (with RestClient 2.4, for the test) :
{
"camp":{
"total": 100,
"number": "epw1f6e"
},
"machine":{
"serial_number": "1234567",
"token": "fONxDN"
}
}
Camp controller :
def create
if is_it_json?
logger.debug params.inspect
machine = Machine.find_by_serial_number(params[:machine][:serial_number])
...
From the logger, I get that params are : {"action"=>"create", "controller"=>"camp"}
Where is the json information??
My log error :
Started POST "/camps" for 127.0.0.1 at 2012-07-15 00:08:21 +0100
Processing by CampsController#create as JSON
WARNING: Can't verify CSRF token authenticity
{"action"=>"create", "controller"=>"camps"}
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `[]' for nil:NilClass):
app/controllers/camps_controller.rb:24:in `create'
What might i be doing wrong?
Thank you
After a lot of reading and questioning, i just found out the solution :
The params weren't getting filled because i was missing Headers (I had the Accept, but was missing the Content-type) :
Accept: application/json
Content-type: application/json
Adding the headers solved this issue.
Can't verify CSRF token authenticity {"action"=>"create", "controller"=>"camps"}
Completed 500 Internal Server Error in 2ms
That error is thrown when an invalid (or nonexistent) CSRF token is posted with your json. The CSRF needs to be attached to the header of any posted data. For testing you can disable CSRF tokens by adding the following to your controller (for Rails 3):
protect_from_forgery :except => :create
Do not leave that in your controller when the site goes into production. CSRF tokens prevent CSRF attacks. Refer to the Ruby on Rails Security Guide for more details.
Let me know if that does the trick!
Related
Hi I have rails 5 application which is throwing following errors
Can't verify CSRF token authenticity. ActionController::InvalidAuthenticityToken error when submitting a POST request for signin in staging environment. It's weird because form is working fine for Production and development environment. Here is the request param
{
"method":"POST",
"path":"/users/sign_in",
"format":"html",
"controller":"Users::SessionsController",
"action":"create",
"status":422,
"error":"ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken",
"duration":11.53,
"view":0.0,
"params":{
"utf8":"✓",
"authenticity_token":"LDPxQ17rH9W/AoW1Hfeyd4in1Ms7snMuys6IyFIlB6K9JoCLanfjHg6OOcqlf/HkE9pPzEuOwVz3d29iwYaJbA==",
"user":{
"email":"",
"password":"[FILTERED]"
},
"commit":"Login"
},
"#timestamp":"2018-05-23T12:08:26.463Z",
"#version":"1",
"message":"[422] POST /users/sign_in (Users::SessionsController#create)"
}
You can add this to the controller
skip_before_action :verify_authenticity_token
Of course it's not recommended to do this, but for some reason it solved my problems, since it happen on one form only on my whole application and it was safe to skip this auth.
ERROR MSG:
Error: Request failed with status code 500
Stack trace:
[42]/</t.exports#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:89311
[42]/</t.exports#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:251725
[42]/</t.exports/</d[h]#http://crdwk.herokuapp.com/packs/bundle-ecc8ea14dbe153e50352.js:1:88311
Ruby version: 2.3
Rails version: 5.1
I have a server-side rendered, client-side hydrated React/Rails app (using gem 'react-rails').
I added the gem 'rack-cors' plus setup in application.rb in order for my requests to work (I'm using axios). However, signing out (a DELETE request) fails and hitting refresh erases the current user. Neither issue occurs locally/in development.
Here's the app: http://crdwk.herokuapp.com
And the repo: https://github.com/English3000/crdwk
I took a look at my Heroku logs:
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `reset_token' for nil:NilClass):
app/controllers/application_controller.rb:29:in `sign_out'
app/controllers/api/sessions_controller.rb:3:in `destroy'
Given that hitting refresh, the current user does not persist, the issue is the current user somehow isn't getting set.
However, this is not an issue in development. Why would that be?
Looking through my project, the only difference I can find on the backend as compared with a client-side rendered one (which I literally copy & pasted the code for this project from) is this line in application_controller.rb:
skip_before_action :verify_authenticity_token
However, if I comment out this line, when I try to sign up, I get the server error
Started POST "/api/users" for 127.0.0.1 at 2018-03-05 12:16:57 -0800
Processing by Api::UsersController#create as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:
This is a result of using gem 'react-rails'. (I don't get this error for my other client-side rendered project.)
There isn't an "authenticity_token" parameter.
I find these two resources: Rails security and Learnetto's how-to.
So I add these two lines of code from the second artilce to my api.js:
const csrfToken = document.querySelector("meta[name=csrf-token]").content;
axios.defaults.headers.common["X-CSRF-Token"] = csrfToken;
Now my web app works with the extra application_controller.rb line commented out. EXCEPT, I can't use the DOM to grab the csrf token for my React Native version, so I now have the same issue for mobile...
I am having some trouble working with the MicrosoftGraph Webhook. I think that I am not properly returning HTTP response, because when I put a binding.pry into my controller, after making the request it hits the controller.
However, the request seems to timeout before hitting my controller (see stack trace below). Here is my controller code and subscription request code, and stack trace. I really appreciate the help.
def self.create_subscription(user)
callback = Proc.new do |r|
r.headers['Authorization'] = "Bearer #{user.outlook_token.access_token}"
r.headers['Content-Type'] = 'application/json'
r.headers['X-AnchorMailbox'] = user.email
end
path = 'subscriptions'
data = {
changeType: "created, updated",
notificationUrl: "https://my_url/api/watch/outlookNotification",
resource: "me/mailFolders('Inbox')/messages",
expirationDateTime:"2017-08-19T06:23:45.9356913Z",
clientState: "subscription-identifier"
}
graph = MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
&callback)
response = graph.service.post(path, data.to_json)
end
def outlook_webhook
#token = params[:validationToken]
head 200, content_type: "text/plain", content_length: 7
response.body = #token
end
Completed 500 Internal Server Error in 14613ms (ActiveRecord: 478.4ms)
OData::ClientError (400 InvalidRequest: "Subscription validation
request timed out." from
"https://graph.microsoft.com/v1.0/subscriptions"):
app/models/outlook_wrapper.rb:44:in create_subscription'
app/controllers/business/messages_controller.rb:18:inindex'
Rendered
/Users/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_source.erb
(7.9ms) Rendered
/Users/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.9ms) Rendered
/Users/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
(3.8ms) Rendered
/Users/.rbenv/versions/2.1.2/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
(176.2ms)
Started POST
"/api/watch/outlookNotification?validationToken=YTJhMTk5MDQtYjdmOC00ZjYxLWIzOGEtMDczM2FjMTAxZTBj"
for 52.161.110.176 at 2017-08-23 12:29:05 -0400 Processing by
InboundEmailsController#outlook_webhook as HTML Parameters:
{"validationToken"=>"YTJhMTk5MDQtYjdmOC00ZjYxLWIzOGEtMDczM2FjMTAxZTBj"}
Completed 200 OK in 35ms (ActiveRecord: 0.0ms)
A Content-Length of 7 is not large enough to accommodate the validation token.
As far as the request timing out, when testing locally, is notificationUrl a publicly accessible URL? If you're using something like http://localhost/api/watch/outlookNotification, then Microsoft will not know how to access your webhook since localhost is not a publicly accessible host.
Even if you do provide a publicly accessible host, you'll still need to poke a hole in your firewall. My suggestion is to use ngrok when testing locally and use an environment variable to set the host.
Run ngrok http 3000 in a console and it will give you a URL that looks something like https://d83375e5.ngrok.io. While ngrok is running, it will forward HTTP and HTTPS requests from d83375e5.ngrok.io to your computer on port 3000.
If you use a notificationUrl like https://${ENV['WEBHOOK_HOST']}/api/watch/outlookNotification, then in development, set the environment variable WEBHOOK_HOST to the host provided by ngrok. In production, you don't need to run ngrok; just set WEBHOOK_HOST to the publicly accessible host for your server.
I may be a little late to the party, but I ran into this same issue. The development environment in rails blocks multiple requests which is why you are getting a timeout. Since you are waiting for a response from the post while Graph is blasting a request back, the request will be blocked until you receive a response from your first post.
As it seems you have discovered, when running in prod this is not an issue as the production environment settings do not block multiple requests.
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
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)
Rails 3.1.3, ruby 1.9.3p374
I am trying to POST from a controller (which receives data via POST from client and then does some processing first) to another controller in the app, and am getting Timeout::Error.
I have tried using Net::HTTP (long form below, also did shortcut form):
uri = URI.parse(credit_payments_url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
auth_token = params[:authenticity_token]
request.set_form_data({:cc => "test", :authenticity_token => auth_token })
response = http.request(request)
And HTTParty:
auth_token = params[:authenticity_token]
HTTParty.post(credit_payments_url, :body => {:cc => "test", :authenticity_token => auth_token})
In both cases, I get the Timeout::Error, and also see this in the server output:
Started POST "/payments/credit" for 127.0.0.1 at 2013-02-19 17:39:35 -0600
Processing by PaymentsController#credit as HTML
Parameters: {"cc"=>"test", "authenticity_token"=>"px+YzdbEfC5p2i3e5yjNT4EQy4WMA9aEWY/v2tfdFhA="}
WARNING: Can't verify CSRF token authenticity
credit_payments_url is the correct url and there is a corresponding route. I've been getting the CSRF warning so I added :authenticity_token from the original request but the CSRF warning still shows up. I'm not sure if that has anything to do with the POST timing out.
I feel like there may be some basic network or configuration issue causing the POST to not work, but can't quite tell what it is. Any ideas?
First - Probably, you have just one worker, busy in this request, and therefore unable to respond the second request. Try to make the post inside a thread, or use more than one worker.
Second - Why are you posting to the app itself? Why don't you dry the code, extracting the needed code from the other action to a method, and calling it in both places?