malcoauri
malcoauri

Reputation: 12189

How to fix InvalidAuthenticityToken in Rails?

I'm developing some API for my mobile application, and I got the following error in some POST action:

ActionController::InvalidAuthenticityToken

Code of my ActionController:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

I know how I can fix it through disabling CSRF verification, but in this case my API will be unsafe for CSRF attacks. Please, tell me, how to fix this error without disabling CSRF protection? Thanks. I use Rails 4.

Upvotes: 1

Views: 606

Answers (2)

Niall Paterson
Niall Paterson

Reputation: 3580

Rails only looks for an authenticity token for html/js requests, not json/xml ones, so this probably isn't an issue with rails, it's actually probably something to do with incorrect headers being passed in. Make sure you're passing in

Content-Type: application/json

client side, otherwise rails will think this is html. You can test this with curl:

curl -H "Content-Type: application/json" -X POST http://example.com/...

Also as a side note, as rails says, you should use

protect_from_forgery with: :null_session

not

protect_from_forgery with: :exception

Upvotes: 1

junil
junil

Reputation: 768

get the session[:_csrf_token] (you can create an api to get the csrf_token for the current session) before sending the post request so that you can send it with the parameters..Rails check for authenticity token for all requests other than GET.

https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L242

Upvotes: 0

Related Questions