Rails: Can't verify CSRF token authenticity when making a POST request
Cross site request forgery (CSRF/XSRF) is when a malicious web page tricks users into performing a request that is not intended for example by using bookmarklets, iframes or just by creating a page which is visually similar enough to fool users.
The Rails CSRF protection is made for "classical" web apps - it simply gives a degree of assurance that the request originated from your own web app. A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.
However an API is usually by definition cross site and meant to be used in more than your web app, which means that the whole concept of CSRF does not quite apply.
Instead you should use a token based strategy of authenticating API requests with an API key and secret since you are verifying that the request comes from an approved API client - not from your own app.
You can deactivate CSRF as pointed out by @dcestari:
class ApiController < ActionController::Base
protect_from_forgery with: :null_session
end
Updated. In Rails 5 you can generate API only applications by using the --api
option:
rails new appname --api
They do not include the CSRF middleware and many other components that are superflouus.
- http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf
- https://labs.kollegorna.se/blog/2015/04/build-an-api-now/
- WARNING: Can't verify CSRF token authenticity rails
Another way to turn off CSRF that won't render a null session is to add:
skip_before_action :verify_authenticity_token
in your Rails Controller. This will ensure you still have access to session info.
Again, make sure you only do this in API controllers or in other places where CSRF protection doesn't quite apply.
There is relevant info on a configuration of CSRF with respect to API controllers on api.rubyonrails.org:
⋮
It's important to remember that XML or JSON requests are also affected and if you're building an API you should change forgery protection method in
ApplicationController
(by default::exception
):class ApplicationController < ActionController::Base protect_from_forgery unless: -> { request.format.json? } end
We may want to disable CSRF protection for APIs since they are typically designed to be state-less. That is, the request API client will handle the session for you instead of Rails.
⋮