William Hu
William Hu

Reputation: 16141

Rails 5 devise_token_auth Can't verify CSRF token authenticity

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!

Upvotes: 6

Views: 4168

Answers (1)

Tan Nguyen
Tan Nguyen

Reputation: 3376

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.

Upvotes: 7

Related Questions