. Advertisement .
..3..
. Advertisement .
..4..
Hello everyone, I’m back here. Today, I’m attempting to publish a post to my local development site, then I have struggle with error: “Can not verify csrf token authenticity”, which looks like this:
HTTParty.post('http://localhost:3000/fetch_heroku',
:body => {:type => 'product'},)
However, when I try to post, the server returns an error:
Started POST "/fetch_heroku" for 127.0.0.1 at 2016-02-03 23:33:39 +0800
ActiveRecord::SchemaMigration Load (0.0ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by AdminController#fetch_heroku as */*
Parameters: {"type"=>"product"}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 1ms
Here’s how I put up my controller and routes; it’s really easy:
def fetch_heroku
if params[:type] == 'product'
flash[:alert] = 'Fetch Product From Heroku'
Heroku.get_product
end
end
post 'fetch_heroku' => 'admin#fetch_heroku'
What should I do now that I’m not sure what to do? Is there anything else I need to set up? Is there anyone who can tell me how to fix this? Thanks!!!
The cause:
After looking over your progarm, I found that you can’t post to your local dev because rails CSRF protection is trying to block cross web API usage.
Rails CSRF protection is used in some old web applications to ensure that the post request comes from the web owner. This option is needed since many websites currently have a lot of fake requests (CSRF / XSRF). To deceive users, malicious websites frequently use bookmarklets and iframes. Rails creates a CSRF token at random and saves it in the session. Rails will check if the token matches the session storage when you post.
However, the API is cross-site and widely used in many web apps, therefore the CSRF standards do not fully apply.
Solution:
Instead, since you’re confirming that the request originates from an authorised API client – not your own app – you should utilize a token-based technique of authenticating API queries with an API key and secret.
You can disable CSRF by this:
Note: The —api option in Rails 5 allows you to create API-only applications:
They exclude the CSRF middleware and a slew of other high-value components.
I hope you can fix your error with my suggestion! Good luck!!!!