0

I have an api setup in my rails application, and after creating my first form and trying to post something I encountered this error:

Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken  - ActionController::InvalidAuthenticityToken:

I have read plenty of posts that recommended things like this:

$.ajaxSetup({
        headers: {
        'X-Transaction': 'POST Example',
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        },
    })

or passing form_authenticity_token directly to my javascript (as this is a remote form), but nothing works. Still the same error.

Does anyone know how to solve it?

3
  • It's usually better practice to disable CSRF for API, and use another authentication to protect. Commented Feb 1, 2017 at 23:02
  • What would you suggest, James Chen? Commented Feb 1, 2017 at 23:04
  • 1
    If you have a base API controller, you could add this to that API base controller: skip_before_action :verify_authenticity_token. Using which authentication method for the API is a case to case thing and you should search and find one suitable for your project. Commented Feb 1, 2017 at 23:14

1 Answer 1

2

You can use this:

class MyController < ActionController::Base
  protect_from_forgery with: :null_session
end

Authenticating to an API should be done usually with a key and secret instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Am I supposed to use it inside my ApplicationController, or inside my ApiControllers?
I will actually stick to it. Do you have any articles/ tuts that you can recommend how to use key and secret to authenticate api?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.