6

I am working on a Rails 5 api project which is used by mobile client with gem devise_token_auth for authorization.

I am clear about what the warning means.

1st Question: CSRF protect should be turned OFF for api(JSON/XML)respond, correct?

I searched some on web it seems CSRF just happens on web application with cookie. But i read this from rails api document:

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

So i still get the warning by adding like this:

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
  include DeviseTokenAuth::Concerns::SetUserByToken
end

2nd Question: If API doesn't need CSRF protection, why

protect_from_forgery unless: -> { request.format.json? }

doesn't work?

Not sure if i understood something wrong. Thank you!

William Hu
  • 15,423
  • 11
  • 100
  • 121

1 Answers1

7

the code should be:

protect_from_forgery with: :null_session, if: ->{request.format.json?}

You might have to use null_session for API, it provides an empty session during request but doesn't reset it completely. Used as default if :with option is not specified.

Tan Nguyen
  • 3,281
  • 1
  • 18
  • 18